给定一个由 '1'(陆地)和 '0'(水)组成的的二维网格,计算岛屿的数量。一个岛被水包围,并且它是通过水平方向或垂直方向上相邻的陆地连接而成的。你可以假设网格的四个边均被水包围。
示例 1:
输入:
11110
11010
11000
00000
输出: 1
示例 2:
输入:
11000
11000
00100
00011
输出: 3
class Solution {
public:
void DFS(vector
{
mark[x][y] = 1;
static const int dx[] = {-1,1,0,0};
static const int dy[] = {0,0,-1,1};
for(int i = 0;i < 4;i++)
{
int newx = x + dx[i];
int newy = y + dy[i];
if(newx < 0 || newx >= mark.size() || newy < 0 || newy >= mark[newx].size())
{
continue;
}
if(mark[newx][newy] == 0 && grid[newx][newy] == '1')
DFS(mark,grid,newx,newy);
}
}
void BFS(vector
{
static const int dx[] = {-1,1,0,0};
static const int dy[] = {0,0,-1,1};
queue
q.push(make_pair(x,y));
mark[x][y] = 1;
while(!q.empty())
{
x = q.front().first;
y = q.front().second;
q.pop();
for(int i = 0;i < 4;i++)
{
int newx = x + dx[i];
int newy = y + dy[i];
if(newx < 0 || newx >= mark.size() || newy < 0 || newy >= mark[newx].size())
{
continue;
}
if(mark[newx][newy] == 0 && grid[newx][newy] == '1')
{
q.push(make_pair(newx,newy));
mark[newx][newy] = 1;
}
}
}
}
int numIslands(vector
vector
int island_num = 0;
for(int i = 0;i < grid.size();i++)
{
mark.push_back(vector
for(int j = 0;j < grid[i].size();j++)
{
mark[i].push_back(0);
}
}
for(int i = 0;i < grid.size();i++)
{
for(int j = 0;j < grid[i].size();j++)
{
if(grid[i][j] == '1' && mark[i][j] == 0)
{
//DFS(mark,grid,i,j);
BFS(mark,grid,i,j);
island_num++;
}
}
}
return island_num;
}
};