Skip to content

Commit 93d4c8b

Browse files
[BOJ] 27211 도넛 행성 (G5)
1 parent d44afdc commit 93d4c8b

File tree

2 files changed

+69
-1
lines changed

2 files changed

+69
-1
lines changed

서정우/7주차/260209.js

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
const fs = require("fs");
2+
const filePath = process.platform === "linux" ? "/dev/stdin" : "./서정우/input.txt";
3+
const input = fs.readFileSync(filePath).toString().trim().split("\n");
4+
5+
// N 세로 M 가로
6+
const [N, M] = input[0].split(" ").map(Number);
7+
8+
const board = input.slice(1).map((row) => row.split(" ").map(Number));
9+
10+
const isOutOfMap = (row, col) => row < 0 || row >= N || col < 0 || col >= M;
11+
12+
const visited = Array.from({ length: N }, () => Array(M).fill(0));
13+
14+
const actions = [
15+
[1, 0],
16+
[-1, 0],
17+
[0, 1],
18+
[0, -1],
19+
];
20+
21+
const bfs = (row, col) => {
22+
const q = [[row, col]];
23+
if (visited[row][col]) {
24+
return 0;
25+
}
26+
27+
while (q.length > 0) {
28+
const [row, col] = q.shift();
29+
visited[row][col] = 1;
30+
31+
actions.forEach(([ar, ac]) => {
32+
const nextPos = [row + ar, col + ac];
33+
const [nextRow, nextCol] = nextPos;
34+
35+
if (isOutOfMap(nextRow, nextCol)) {
36+
if (nextRow < 0) nextPos[0] = N - 1;
37+
else if (nextRow >= N) nextPos[0] = 0;
38+
if (nextCol < 0) nextPos[1] = M - 1;
39+
else if (nextCol >= M) nextPos[1] = 0;
40+
}
41+
42+
if (board[nextPos[0]][nextPos[1]] === 0 && !visited[nextPos[0]][nextPos[1]]) {
43+
q.push(nextPos);
44+
visited[nextPos[0]][nextPos[1]] = 1;
45+
}
46+
});
47+
}
48+
49+
return 1;
50+
};
51+
52+
let count = 0;
53+
for (let i = 0; i < N; i++) {
54+
for (let j = 0; j < M; j++) {
55+
if (board[i][j] === 0 && !visited[i][j]) {
56+
count += bfs(i, j);
57+
}
58+
}
59+
}
60+
61+
console.log(count);

서정우/input.txt

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,8 @@
1-
December 31, 2007 23:59
1+
7 8
2+
0 0 1 1 0 0 0 0
3+
0 1 1 1 1 0 1 0
4+
1 1 1 1 1 1 1 1
5+
0 1 1 1 1 1 0 0
6+
1 1 0 0 0 1 0 0
7+
0 1 0 0 0 1 0 1
8+
0 0 1 1 1 1 0 0

0 commit comments

Comments
 (0)