200. Number of Islands (Graph)
DFS把能遍历到的是1的都变成0,这样就能识别出一个岛。
1 class Solution { 2 public int numIslands(char[][] grid) { 3 if(grid == null) return 0; 4 if(grid.length == 0) return 0; 5 int n = grid.length; 6 int m = grid[0].length; 7 int count = 0; 8 for(int i = 0; i < n; i++) { 9 for(int j = 0; j < m; j++) { 10 if(grid[i][j] == '1') { 11 dfs(grid, i, j); 12 count++; 13 14 } 15 16 } 17 } 18 return count; 19 20 21 } 22 23 public void dfs(char[][] grid, int i, int j) { 24 if(i >= 0 && j >= 0 && i < grid.length && j < grid[0].length && grid[i][j] == '1') { //grid[i][j]判断条件要写在最后 不然会outofbound 25 grid[i][j] = '0'; 26 dfs(grid, i - 1, j); 27 dfs(grid, i + 1, j); 28 dfs(grid, i, j - 1); 29 dfs(grid, i, j + 1); 30 } 31 32 } 33 }