|
1 | 1 | class Solution {
|
| 2 | + int[][] dirs = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; |
2 | 3 | public int numIslands(char[][] grid) {
|
3 |
| - int count = 0; |
| 4 | + if (grid.length == 0 || grid[0].length == 0) { |
| 5 | + return 0; |
| 6 | + } |
| 7 | + |
| 8 | + int countOfIslands = 0; |
| 9 | + boolean[][] visited = new boolean[grid.length][grid[0].length]; |
| 10 | + int numOfRows = grid.length; |
| 11 | + int numOfCols = grid[0].length; |
4 | 12 |
|
5 |
| - for (int i=0; i<grid.length; i++) { |
6 |
| - for (int j=0; j<grid[i].length; j++) { |
7 |
| - if (grid[i][j] == '1') { |
8 |
| - count++; |
9 |
| - |
10 |
| - markArea(grid, i, j); |
| 13 | + for (int i = 0; i < numOfRows; i++) { |
| 14 | + for (int j = 0; j < numOfCols; j++) { |
| 15 | + if (visited[i][j] || grid[i][j] == '0') { |
| 16 | + continue; |
11 | 17 | }
|
| 18 | + |
| 19 | + dfs(grid, i, j, numOfRows, numOfCols, visited); |
| 20 | + countOfIslands++; |
12 | 21 | }
|
13 | 22 | }
|
14 | 23 |
|
15 |
| - return count; |
| 24 | + return countOfIslands; |
16 | 25 | }
|
17 | 26 |
|
18 |
| - private void markArea(char[][] grid, int i, int j) { |
19 |
| - if (i < 0 || j < 0 || i >= grid.length || j >= grid[i].length || grid[i][j] == '0') { |
| 27 | + private void dfs(char[][] grid, int x, int y, int numOfRows, int numOfCols, boolean[][] visited) { |
| 28 | + if (x < 0 || x >= numOfRows || y < 0 || y >= numOfCols || visited[x][y]) { |
| 29 | + return; |
| 30 | + } |
| 31 | + |
| 32 | + visited[x][y] = true; |
| 33 | + if (grid[x][y] == '0') { |
20 | 34 | return;
|
21 | 35 | }
|
22 | 36 |
|
23 |
| - grid[i][j] = '0'; |
24 |
| - markArea(grid, i-1, j); |
25 |
| - markArea(grid, i, j-1); |
26 |
| - markArea(grid, i, j+1); |
27 |
| - markArea(grid, i+1, j); |
| 37 | + for (int[] dir : dirs) { |
| 38 | + dfs(grid, x + dir[0], y + dir[1], numOfRows, numOfCols, visited); |
| 39 | + } |
28 | 40 | }
|
29 | 41 | }
|
0 commit comments