- Number of Islands
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:
11110110101100000000
Answer: 1
Example 2:
11000110000010000011
Answer: 3
Credits:Special thanks to @mithmatt for adding this problem and creating all test cases.
public class Solution {
public int numIslands(char[][] grid) {
if(grid.length == 0 || grid[0].length == 0) return 0;
int sum = 0;
for(int i = 0; i < grid.length; i++)
for(int j = 0; j < grid[0].length; j++)
sum += dfs(grid,i,j);
return sum;
}
private int dfs(char[][] grid, int i, int j){
if(grid[i][j] == '0') return 0;
grid[i][j] = '0';
int[][] dir = {{0,-1} , {0,1} ,{-1,0} ,{1,0}};
for(int m = 0; m < dir.length; m++){
int x = i+dir[m][0], y = j+dir[m][1];
if(x >= 0 && x < grid.length && y >= 0 && y < grid[0].length && grid[x][y] == '1')
dfs(grid,x,y);
}
return 1;
}
}
网友评论