|
| 1 | +/** |
| 2 | + * TC: O(ROW * COLUMN) |
| 3 | + * ์ฃผ์ด์ง grid ๋ฐฐ์ด ์ ์ฒด ์ํ + (์ต์
์ ๊ฒฝ์ฐ queue์์ grid ์ ์ฒด ์ํ) |
| 4 | + * |
| 5 | + * SC: O(ROW * COLUMN) |
| 6 | + * queue์์ ์ต๋ grid๋งํผ ์ํ |
| 7 | + * |
| 8 | + * ROW: grid.length, COLUMN: grid[0].length |
| 9 | + */ |
| 10 | + |
| 11 | +/** |
| 12 | + * @param {character[][]} grid |
| 13 | + * @return {number} |
| 14 | + */ |
| 15 | +var numIslands = function (grid) { |
| 16 | + const LAND = "1"; |
| 17 | + const VISITED_LAND = "#"; |
| 18 | + const ROW = grid.length; |
| 19 | + const COLUMN = grid[0].length; |
| 20 | + |
| 21 | + // 1. ์ํ์ข์ฐ ๋ฐฉํฅํค |
| 22 | + const DIRECTION = [ |
| 23 | + { r: 0, c: 1 }, |
| 24 | + { r: 1, c: 0 }, |
| 25 | + { r: 0, c: -1 }, |
| 26 | + { r: -1, c: 0 }, |
| 27 | + ]; |
| 28 | + |
| 29 | + let numberOfIslands = 0; |
| 30 | + |
| 31 | + // 2. ์ ์ฒด ์ํํ๋ฉด์ |
| 32 | + for (let row = 0; row < ROW; row++) { |
| 33 | + for (let column = 0; column < COLUMN; column++) { |
| 34 | + // 3. LAND๋ฅผ ๋ฐ๊ฒฌํ๋ฉด ๋ฐฉ๋ฌธํ ์ฌ์ผ๋ก ํ์(bfs)ํ๊ณ ์ฌ๊ฐฏ์ ๊ฐฑ์ |
| 35 | + if (grid[row][column] === LAND) { |
| 36 | + bfs(row, column); |
| 37 | + numberOfIslands += 1; |
| 38 | + } |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + return numberOfIslands; |
| 43 | + |
| 44 | + function bfs(startRow, startColumn) { |
| 45 | + // 4. ์์์ขํ queue์ ๋ฃ๊ณ ๋ฐฉ๋ฌธ ํ์ |
| 46 | + const queue = [[startRow, startColumn]]; |
| 47 | + grid[startRow][startColumn] = VISITED_LAND; |
| 48 | + |
| 49 | + while (queue.length > 0) { |
| 50 | + const [row, column] = queue.shift(); |
| 51 | + |
| 52 | + // 5. ์ํ์ข์ฐ์ ์ขํ๋ฅผ ๊ฐ์ง๊ณ |
| 53 | + for (const direction of DIRECTION) { |
| 54 | + const nextRow = row + direction.r; |
| 55 | + const nextColumn = column + direction.c; |
| 56 | + |
| 57 | + // 6. ์ ํจํ ์ขํ && ๋ฏธ๋ฐฉ๋ฌธ ์ก์ง์ธ์ง ํ์ธ |
| 58 | + if ( |
| 59 | + isValidPosition(nextRow, nextColumn) && |
| 60 | + grid[nextRow][nextColumn] === LAND |
| 61 | + ) { |
| 62 | + // 7. queue์ ์ถ๊ฐํ๊ณ ๋ฐฉ๋ฌธ ํ์ |
| 63 | + grid[nextRow][nextColumn] = VISITED_LAND; |
| 64 | + queue.push([nextRow, nextColumn]); |
| 65 | + } |
| 66 | + } |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + // 8. ์ฃผ์ด์ง 2์ฐจ์ ๋ฐฐ์ด์ ์ ํจํ ์ขํ์ธ์ง ํ์ธํ๋ ํจ์ |
| 71 | + function isValidPosition(row, column) { |
| 72 | + if (row < 0 || ROW <= row) { |
| 73 | + return false; |
| 74 | + } |
| 75 | + if (column < 0 || COLUMN <= column) { |
| 76 | + return false; |
| 77 | + } |
| 78 | + return true; |
| 79 | + } |
| 80 | +}; |
0 commit comments