|
| 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); |
0 commit comments