|
| 1 | +class Solution { |
| 2 | + public int numIslands(char[][] grid) { |
| 3 | + // bfs |
| 4 | + // 시간복잡도 : O(r * c), 공간복잡도 O(r * c) |
| 5 | + // 풀이 |
| 6 | + // bfs 풀이에 방문을 Set<String>으로 설정하여 체크, directions(상하좌우)를 통해 탐색 |
| 7 | + // 응용 가능 : 대각선 추가하여 연결된 섬 체크 |
| 8 | + int islands = 0; |
| 9 | + int rows = grid.length; |
| 10 | + int cols = grid[0].length; |
| 11 | + Set<String> visited = new HashSet<>(); |
| 12 | + |
| 13 | + int[][] directions = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; |
| 14 | + |
| 15 | + for (int r = 0; r < rows; r++) { |
| 16 | + for (int c = 0; c < cols; c++) { |
| 17 | + if (grid[r][c] == '1' && !visited.contains(r + "," + c)) { |
| 18 | + islands++; |
| 19 | + bfs(grid, r, c, visited, directions, rows, cols); |
| 20 | + } |
| 21 | + } |
| 22 | + } |
| 23 | + |
| 24 | + return islands; |
| 25 | + } |
| 26 | + |
| 27 | + private void bfs(char[][] grid, int r, int c, Set<String> visited, int[][] directions, int rows, int cols) { |
| 28 | + Queue<int[]> q = new LinkedList<>(); |
| 29 | + visited.add(r + "," + c); |
| 30 | + q.add(new int[]{r, c}); |
| 31 | + |
| 32 | + while (!q.isEmpty()) { |
| 33 | + int[] point = q.poll(); |
| 34 | + int row = point[0], col = point[1]; |
| 35 | + |
| 36 | + for (int[] direction : directions) { |
| 37 | + int nr = row + direction[0], nc = col + direction[1]; |
| 38 | + if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && grid[nr][nc] == '1' && !visited.contains(nr + "," + nc)) { |
| 39 | + q.add(new int[] {nr, nc}); |
| 40 | + visited.add(nr + "," + nc); |
| 41 | + } |
| 42 | + } |
| 43 | + } |
| 44 | + } |
| 45 | +} |
0 commit comments