|
| 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