# Middle-题目80：200. Number of Islands

62人阅读 评论(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:
11110
11010
11000
00000
Example 2:
11000
11000
00100
00011

public class Solution {
public int numIslands(char[][] grid) {
if (grid.length==0 || grid[0].length==0)
return 0;
int count = 0;
boolean[][] visited = new boolean[grid.length][grid[0].length];
for (int i=0; i<grid.length; i++) {
for (int j=0; j<grid[0].length; j++) {
if (grid[i][j]=='1' && !visited[i][j]) {
count++;
dfs(grid, visited, i, j);
}
}
}
return count;
}

private void dfs(char[][] grid, boolean[][] visited, int row, int col) {
if (row<0 || row>=grid.length || col<0 || col>=grid[0].length || visited[row][col] || grid[row][col]=='0') // grid[i][j] is out of range
return;
visited[row][col] = true;
dfs(grid, visited, row-1, col);
dfs(grid, visited, row+1, col);
dfs(grid, visited, row, col-1);
dfs(grid, visited, row, col+1);
}
}

5ms,beats 25.10%，众数3ms,40.17%
Cmershen的碎碎念：

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：56030次
• 积分：3202
• 等级：
• 排名：第10679名
• 原创：270篇
• 转载：53篇
• 译文：0篇
• 评论：7条
文章分类
最新评论