๋ฌธ์
https://www.acmicpc.net/problem/2667
ํ์ด
์ผ๋จ ์ง๋๋ฅผ 2์ฐจ์๋ฐฐ์ด ํํ๋ก ๋ณํ์์ผฐ๊ณ ์ด๋ฅผ ์ด์ฉํด์ ๋จ์ง๋ณ๋ก ์ํํธ๋ฅผ ๋ฌถ์๋ค.
dfs๋ฅผ ์ด์ฉํด์ ํน์ ์ํํธ์์ ๊ฐ์ ์๋ ๋ชจ๋ ์ํํธ๋ฅผ ํ๋์ ๋จ์ง๋ก ๋ฌถ์๊ณ ๊ทธ ๊ณผ์ ์์ ๋จ์ง๋ด์ ์ํํธ์ ๊ฐฏ์๋ฅผ ํ์ธํ๋ค.
๊ทธ๋ ๊ฒ apartment ๋ผ๋ array์ ๋จ์ง๋ด์ ์ํํธ ๊ฐฏ์๋ฅผ push ํ๋ค ๋ค์ ์ํํธ๊ฐฏ์๋ฅผ ์ค๋ฆ์ฐจ์์ผ๋ก ์ ๋ ฌํ์ฌ ๋ฌธ์ ์ ๋ต์ ๊ตฌํ ์ ์์๋ค.
let fs = require("fs");
let input = fs.readFileSync("/dev/stdin").toString().trim().split("\n");
let N = Number(input.shift());
// ์ง๋ 2์ฐจ์ ๋ฐฐ์ด๋ก ์ ์ฅ
let map = [];
// ๋จ์ง๋ณ ์ง ์๋ฅผ ๋ด์ ๋ฐฐ์ด
let apartment = [];
input.forEach((str) => {
let line = str.split("").map((n) => Number(n));
map.push(line);
});
// ๋จ์ง๋ด ์ํํธ ๊ฐฏ์ count
let apartmentCnt = 0;
let recursive = (r, c) => {
// ๋์๋จ๋ถ
let diffRow = [0, 0, 1, -1];
let diffCol = [1, -1, 0, 0];
for (let direction = 0; direction < 4; ++direction) {
let [nextRow, nextCol] = [r + diffRow[direction], c + diffCol[direction]];
if (map[nextRow] && map[nextRow][nextCol] && map[nextRow][nextCol] === 1) {
map[nextRow][nextCol] = 0;
++apartmentCnt;
recursive(nextRow, nextCol);
}
}
};
for (let row = 0; row < N; ++row) {
for (let col = 0; col < N; ++col) {
if (map[row][col] === 1) {
apartmentCnt = 1;
map[row][col] = 0;
recursive(row, col);
apartment.push(apartmentCnt);
}
}
}
apartment.sort((a, b) => a - b);
console.log(String(apartment.length));
console.log(apartment.join("\n"));
ํ๊ธฐ
์์ฃผ ์ ํ๋ ๋ฌธ์ ์ ํ์ด๋ผ ์ฝ๊ฒ ํ ์ ์์๋ค.
'๐Algorithm' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
๋ฐฑ์ค[node.js] > 14940๋ฒ ์ฌ์ด ์ต๋จ๊ฑฐ๋ฆฌ (0) | 2024.12.30 |
---|---|
๋ฐฑ์ค[node.js] > 10026๋ฒ ์ ๋ก์์ฝ (0) | 2024.12.28 |
๋ฐฑ์ค[node.js] > 2805๋ฒ ๋๋ฌด ์๋ฅด๊ธฐ (1) | 2024.12.21 |
๋ฐฑ์ค[node.js] > 2630๋ฒ ์์ข ์ด ๋ง๋ค๊ธฐ (0) | 2024.12.20 |
๋ฐฑ์ค[node.js] > 1927๋ฒ ์ต์ ํ (0) | 2024.12.19 |