|
| 1 | +import java.util.LinkedList; |
| 2 | +import java.util.Queue; |
| 3 | + |
| 4 | +/** |
| 5 | + * m x n 2D 행렬 grid가 주어질 때 섬의 수를 찾아서 반환하세요. |
| 6 | + * 섬(island)는 물(0)로 둘러싸여 있고 가로 또는 세로로 인접한 섬들과 연결되어 형성되어 있다. |
| 7 | + */ |
| 8 | +class Solution { |
| 9 | + |
| 10 | + int[] dx = {-1, 1, 0, 0}; |
| 11 | + int[] dy = {0, 0, 1, -1}; |
| 12 | + |
| 13 | + public int numIslands(char[][] grid) { |
| 14 | + int cnt = 0; |
| 15 | + for (int i = 0; i < grid.length; i++) { |
| 16 | + for (int j = 0; j < grid[i].length; j++) { |
| 17 | + // land라면 |
| 18 | + if (grid[i][j] == '1') { |
| 19 | + |
| 20 | + // bfs로 섬 탐색 |
| 21 | + bfs(i, j, grid); |
| 22 | + |
| 23 | + // dfs로 섬 탐색 |
| 24 | + dfs(i, j, grid); |
| 25 | + |
| 26 | + cnt++; |
| 27 | + } |
| 28 | + } |
| 29 | + } |
| 30 | + return cnt; |
| 31 | + } |
| 32 | + |
| 33 | + private void dfs(int x, int y, char[][] grid) { |
| 34 | + if (grid[x][y] == '1') { |
| 35 | + grid[x][y] = '0'; |
| 36 | + } |
| 37 | + for (int i = 0; i < 4; i++) { |
| 38 | + int nx = x + dx[i]; |
| 39 | + int ny = y + dy[i]; |
| 40 | + if (nx >= 0 && nx < grid.length && ny >= 0 && ny < grid[0].length && grid[nx][ny] == '1') { |
| 41 | + dfs(nx, ny, grid); |
| 42 | + } |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + private void bfs(int startX, int startY, char[][] grid) { |
| 47 | + |
| 48 | + Queue<int[]> queue = new LinkedList<>(); |
| 49 | + queue.offer(new int[]{startX, startY}); |
| 50 | + grid[startX][startY] = '0'; |
| 51 | + |
| 52 | + while (!queue.isEmpty()) { |
| 53 | + int[] current = queue.poll(); |
| 54 | + for (int i = 0; i < 4; i++) { |
| 55 | + int newX = current[0] + dx[i]; |
| 56 | + int newY = current[1] + dy[i]; |
| 57 | + if (newX >= 0 && newX < grid.length && newY >= 0 && newY < grid[0].length) { |
| 58 | + if (grid[newX][newY] == '1') { |
| 59 | + queue.offer(new int[]{newX, newY}); |
| 60 | + grid[newX][newY] = '0'; |
| 61 | + } |
| 62 | + } |
| 63 | + } |
| 64 | + } |
| 65 | + } |
| 66 | +} |
| 67 | + |
0 commit comments