然后move on 去下一个点...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | public class Solution { HashSet<String> visited = new HashSet<String>(); char[][] grid; public int numIslands(char[][] grid) { this.grid = grid; int total = 0; for (int i = 0; i < grid.length; i++){ for (int j = 0; j < grid[0].length; j++){ if (grid[i][j] == '1' && !visited.contains(""+i+","+j)){ total++; dfs(i, j); } } } return total; } private void dfs(int x, int y){ String location = ""+x+","+y; if (x < 0 || x >= grid.length || y < 0 || y >= grid[0].length || grid[x][y] == '0' || visited.contains(location)){ return; } visited.add(location); dfs(x, y+1); dfs(x, y-1); dfs(x+1, y); dfs(x-1, y); return; } } |
No comments:
Post a Comment