Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.Example 1:11110110101100000000Answer: 1Example 2:11000110000010000011Answer: 3
DFS的Flood Fill方法,
使用額外Visited數(shù)組的做法:
1 public class Solution { 2 public int numIslands(char[][] grid) { 3 if (grid==null || grid.length==0 || grid[0].length==0) return 0; 4 int count = 0; 5 boolean[][] visited = new boolean[grid.length][grid[0].length]; 6 for (int i=0; i<grid.length; i++) { 7 for (int j=0; j<grid[0].length; j++) { 8 if (grid[i][j] != '1') continue; 9 else {10 count++;11 floodFill(grid, i, j, visited);12 }13 }14 }15 return count;16 }17 18 public void floodFill(char[][] grid, int i, int j, boolean[][] visited) {19 if (i<0 || i>=grid.length || j<0 || j>=grid[0].length) return;20 if (visited[i][j]) return;21 if (grid[i][j] != '1') return;22 grid[i][j] = '2';23 floodFill(grid, i-1, j, visited);24 floodFill(grid, i+1, j, visited);25 floodFill(grid, i, j-1, visited);26 floodFill(grid, i, j+1, visited);27 }28 }
更節(jié)省空間的方法:不使用額外visited數(shù)組,但是用‘1’變成‘2’表示visited的方法
1 public class Solution { 2 public int numIslands(char[][] grid) { 3 if (grid==null || grid.length==0 || grid[0].length==0) return 0; 4 int count = 0; 5 for (int i=0; i<grid.length; i++) { 6 for (int j=0; j<grid[0].length; j++) { 7 if (grid[i][j] != '1') continue; 8 else { 9 count++;10 floodFill(grid, i, j);11 }12 }13 }14 return count;15 }16 17 public void floodFill(char[][] grid, int i, int j) {18 if (i<0 || i>=grid.length || j<0 || j>=grid[0].length) return;19 if (grid[i][j] != '1') return; //either 0(water) or 2(visited)20 grid[i][j] = '2';21 floodFill(grid, i-1, j);22 floodFill(grid, i+1, j);23 floodFill(grid, i, j-1);24 floodFill(grid, i, j+1);25 }26 }
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注