给定一个M N,表示这个整型数组的大小
6 7
0 1 1 1 0 0 1
0 0 1 0 0 0 0
0 0 0 0 1 0 0
0 0 0 1 1 1 0
1 1 1 0 1 0 0
1 1 1 1 0 0 0
0表示海水,1表示陆地,一堆连起来的1表示一个岛屿,求出岛屿数
这个题目是典型题目,我们下面给出BFS的解法:
#include <iostream>
#include <queue>
#define MAXN 100
using namespace std;
struct node{
int x;
int y;
}Node;
int X[4]={0,0,-1,1};
int Y[4]={-1,1,0,0};
int a[MAXN][MAXN];
int n,m;
bool judge(int x,int y)
{
if(x>=m||x<0||y>=n||y<0||a[x][y]==0)
return false;
return true;
}
void bfs(int x,int y)
{
queue<node> q;
Node.x=x; Node.y=y;
q.push(Node);
while(!q.empty())
{
node top=q.front();
q.pop();
for(int i=0;i<4;i++)
{
int new_x=top.x+X[i];
int new_y=top.y+Y[i];
if(judge(new_x,new_y))
{
a[new_x][new_y]=0;
Node.x=new_x;
Node.y=new_y;
q.push(Node);
}
}
}
}
int main()
{
int ans=0;
cin>>m>>n;
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
cin>>a[i][j];
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
if(judge(i,j))
{
bfs(i,j);
ans++;
}
printf("%d\n",ans);
return 0;
}