# Number of Islands

112人阅读 评论(0)

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

Example 2:

11000110000010000011

Credits:

Special thanks to @mithmatt for adding this problem and creating all test cases.

public class Solution {
public int numIslands(char[][] grid) {
if(grid == null || grid.length == 0) return 0;
int m = grid.length;
int n = grid[0].length;
int count = 0;
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
if(grid[i][j] == '1'){
count++;
dfs(grid, i, j);
}
}
}
return count;
}

public void dfs(char[][] grid, int i, int j){
if(i<0 || i>=grid.length || j<0 || j>=grid[0].length || grid[i][j] == '0'){
return;
}
if(grid[i][j] == '1'){
grid[i][j] = '2';
dfs(grid, i-1, j);
dfs(grid, i+1, j);
dfs(grid, i, j-1);
dfs(grid, i, j+1);
}
}
}


0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：110286次
• 积分：4882
• 等级：
• 排名：第6069名
• 原创：394篇
• 转载：13篇
• 译文：0篇
• 评论：1条
阅读排行
评论排行
最新评论