200. Number of Islands
- Total Accepted: 67432
- Total Submissions: 219192
- Difficulty: Medium
- Contributors: Admin
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
解题思路:
本题与前面 poj 2386 作法完全一致,即使用dfs求连通块个数,详细解法请阅读博客 poj 2386 题解。
代码展示:
class Solution {
public:
void dfs(vector<vector<char>>& grid,int x, int y,int row,int col)
{
grid[x][y]='0';
for(int i=-1;i<2;i++)
{
for(int j=-1;j<2;j++)
{
if(abs(i)+abs(j)<2)
{
int nx = x+i;
int ny = y+j;
if(nx>=0&&nx<row&&ny>=0&&ny<col&&grid[nx][ny]=='1')
{
dfs(grid,nx,ny,row,col);
}
}
}
}
}
int numIslands(vector<vector<char>>& grid) {
int row = grid.size();
if(!row) return 0;
int col = grid[0].size();
int ans = 0;
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
if(grid[i][j]=='1')
{
dfs(grid,i,j,row,col);
ans++;
}
}
}
return ans;
}
};