|
| 1 | +/** |
| 2 | + * 문제 설명 |
| 3 | + * - 2차원 그리드에서 섬의 갯수를 구하는 문제 |
| 4 | + * |
| 5 | + * 조건 |
| 6 | + * - 가로, 세로가 1로 인접해있는 경우 같은 섬으로 간주 |
| 7 | + * |
| 8 | + * 아이디어 |
| 9 | + * - 경로 탐색, 네트워크, 조합 유형이 나오면 '그래프 탐색 알고리즘'을 떠울린다. |
| 10 | + * 1) DFS (재귀) |
| 11 | + * 2) BFS (링크드리스트 or 큐) |
| 12 | + * |
| 13 | + */ |
| 14 | + |
| 15 | +function numIslands(grid: string[][]): number { |
| 16 | + const rows = grid.length; |
| 17 | + const cols = grid[0].length; |
| 18 | + let count = 0; |
| 19 | + function dfs(r: number, c: number) { |
| 20 | + if (r < 0 || c < 0 || r >= rows || c >= cols || grid[r][c] === "0") return; |
| 21 | + |
| 22 | + grid[r][c] = "0"; |
| 23 | + dfs(r - 1, c); |
| 24 | + dfs(r + 1, c); |
| 25 | + dfs(r, c - 1); |
| 26 | + dfs(r, c + 1); |
| 27 | + } |
| 28 | + |
| 29 | + for (let r = 0; r < rows; r++) { |
| 30 | + for (let c = 0; c < cols; c++) { |
| 31 | + if (grid[r][c] === "1") { |
| 32 | + count++; |
| 33 | + dfs(r, c); |
| 34 | + } |
| 35 | + } |
| 36 | + } |
| 37 | + return count; |
| 38 | +} |
| 39 | + |
| 40 | +/** |
| 41 | + * |
| 42 | + * BFS version |
| 43 | +
|
| 44 | +function numIslands(grid: string[][]): number { |
| 45 | + const rows = grid.length; |
| 46 | + const cols = grid[0].length; |
| 47 | + let count = 0; |
| 48 | +
|
| 49 | + const directions = [ |
| 50 | + [0, 1], |
| 51 | + [1, 0], |
| 52 | + [0, -1], |
| 53 | + [-1, 0], |
| 54 | + ]; |
| 55 | + function bfs(r: number, c: number) { |
| 56 | + const queue = [[r, c]]; |
| 57 | + grid[r][c] = "0"; |
| 58 | +
|
| 59 | + while (queue.length) { |
| 60 | + const [row, col] = queue.shift()!; |
| 61 | +
|
| 62 | + for (const [dr, dc] of directions) { |
| 63 | + const newRow = row + dr; |
| 64 | + const newCol = col + dc; |
| 65 | +
|
| 66 | + if ( |
| 67 | + newRow >= 0 && |
| 68 | + newRow < rows && |
| 69 | + newCol >= 0 && |
| 70 | + newCol < cols && |
| 71 | + grid[newRow][newCol] === "1" |
| 72 | + ) { |
| 73 | + queue.push([newRow, newCol]); |
| 74 | + grid[newRow][newCol] = "0"; |
| 75 | + } |
| 76 | + } |
| 77 | + } |
| 78 | + } |
| 79 | +
|
| 80 | + for (let r = 0; r < rows; r++) { |
| 81 | + for (let c = 0; c < cols; c++) { |
| 82 | + if (grid[r][c] === "1") { |
| 83 | + count++; |
| 84 | + bfs(r, c); |
| 85 | + } |
| 86 | + } |
| 87 | + } |
| 88 | + return count; |
| 89 | +} |
| 90 | +
|
| 91 | + */ |
0 commit comments