|
| 1 | +import java.util.LinkedList; |
| 2 | +import java.util.Queue; |
| 3 | + |
| 4 | +// BFS 사용 |
| 5 | +// 시간 복잡도 : O(MxN) |
| 6 | +// 공간 복잡도: O(MxN) |
| 7 | +class Solution { |
| 8 | + |
| 9 | + int[][] dir = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; |
| 10 | + |
| 11 | + public int numIslands(char[][] grid) { |
| 12 | + int row = grid.length; |
| 13 | + int col = grid[0].length; |
| 14 | + |
| 15 | + int total = 0; |
| 16 | + for (int i = 0; i < row; i++) { |
| 17 | + for (int j = 0; j < col; j++) { |
| 18 | + if (grid[i][j] == '1') { |
| 19 | + total++; |
| 20 | + BFS(grid, i, j, row, col); |
| 21 | + System.out.println(grid[i][j]); |
| 22 | + } |
| 23 | + } |
| 24 | + } |
| 25 | + return total; |
| 26 | + } |
| 27 | + |
| 28 | + private void BFS(char[][] grid, int r, int c, int sizeR, int sizeC) { |
| 29 | + Queue<Position> queue = new LinkedList<>(); |
| 30 | + |
| 31 | + queue.add(new Position(r, c)); |
| 32 | + grid[r][c] = '0'; // '0'으로 변경 (방문 체크) |
| 33 | + |
| 34 | + while (!queue.isEmpty()) { |
| 35 | + Position current = queue.poll(); |
| 36 | + int curR = current.r; |
| 37 | + int curC = current.c; |
| 38 | + |
| 39 | + for (int i = 0; i < 4; i++) { |
| 40 | + int dirR = dir[i][0]; |
| 41 | + int dirC = dir[i][1]; |
| 42 | + |
| 43 | + int nextR = curR + dirR; |
| 44 | + int nextC = curC + dirC; |
| 45 | + |
| 46 | + if (nextR < 0 || nextR >= sizeR || nextC < 0 || nextC >= sizeC || grid[nextR][nextC] == '0') { |
| 47 | + continue; |
| 48 | + } |
| 49 | + queue.add(new Position(nextR, nextC)); |
| 50 | + grid[nextR][nextC] = '0'; |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + } |
| 55 | + |
| 56 | + static class Position { |
| 57 | + |
| 58 | + int r; |
| 59 | + int c; |
| 60 | + |
| 61 | + Position(int r, int c) { |
| 62 | + this.r = r; |
| 63 | + this.c = c; |
| 64 | + } |
| 65 | + } |
| 66 | +} |
| 67 | + |
0 commit comments