|
| 1 | +/* |
| 2 | +# Time Complexity: O(m * n) |
| 3 | +모든 격자를 최대 2번씩(2중 for loop, dfs 호출) 방문 |
| 4 | +
|
| 5 | +# Space Complexity: O(m * n) |
| 6 | +최악의 경우, 모든 격자가 '1'인 경우에 m * n회 dfs() 재귀 호출이 이뤄진다. 각 콜 스택에서의 파라미터와 지역변수가 상수개 필요하므로, O(m * n) |
| 7 | +*/ |
| 8 | +class Solution { |
| 9 | + public int numIslands(char[][] grid) { |
| 10 | + int m = grid.length; |
| 11 | + int n = grid[0].length; |
| 12 | + int[] dr = {-1, 0, 1, 0}; |
| 13 | + int[] dc = {0, 1, 0, -1}; |
| 14 | + int ans = 0; |
| 15 | + for (int i = 0; i < m; i++) { |
| 16 | + for (int j = 0; j < n; j++) { |
| 17 | + if (grid[i][j] != '1') { |
| 18 | + continue; |
| 19 | + } |
| 20 | + dfs(grid, i, j, dr, dc); |
| 21 | + ans++; |
| 22 | + } |
| 23 | + } |
| 24 | + return ans; |
| 25 | + } |
| 26 | + |
| 27 | + private void dfs(char[][] grid, int r, int c, int[] dr, int[] dc) { |
| 28 | + grid[r][c] = '2'; // mark as visited |
| 29 | + |
| 30 | + for (int i = 0; i < 4; i++) { |
| 31 | + int nr = r + dr[i]; |
| 32 | + int nc = c + dc[i]; |
| 33 | + if (nr < 0 || nr >= grid.length || nc < 0 || nc >= grid[0].length |
| 34 | + || grid[nr][nc] != '1') { |
| 35 | + continue; |
| 36 | + } |
| 37 | + dfs(grid, nr, nc, dr, dc); |
| 38 | + } |
| 39 | + } |
| 40 | +} |
0 commit comments