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:
11110
11010
11000
00000
Answer: 1
Example 2:
11000
11000
00100
00011
Answer: 3
题目含义:所有1连起来可以构成一个岛,求岛的个数
1 private void IslandCount(char[][] grid,int i,int j){ 2 if (i < 0 || i >= grid.length || j < 0 || j >= grid[0].length || grid[i][j] == '0') return; 3 grid[i][j] = '0'; 4 IslandCount(grid, i - 1, j); 5 IslandCount(grid, i + 1, j); 6 IslandCount(grid, i, j - 1); 7 IslandCount(grid, i, j + 1); 8 } 9 10 public int numIslands(char[][] grid) { 11 if (grid.length == 0) return 0; 12 int count = 0; 13 for (int i = 0; i < grid.length; i++) { 14 for (int j = 0; j < grid[0].length; j++) { 15 if (grid[i][j] == '1') { 16 IslandCount(grid, i, j); 17 count++; 18 } 19 } 20 } 21 return count; 22 }