给出一个m*n的矩阵,矩阵中的元素为0或1.称位置(x,y)与其上下左右是相邻的。如果矩阵中有 若干个1
是相邻的,那么称这些1联通。求矩阵中联通的个数。
例如输入: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
输出:4
代码如下:
#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
struct point{
int x;
int y;
}Node;
bool inq[10][10]={false};
int X[4]={0,1,0,-1};
int Y[4]={-1,0,1,0};
int m,n;int map[10][10];int cut=0;
bool judge(int x,int y){
if(x<0||x>=n||y<0||y>=m||map[x][y]==0||inq[x][y]==true){
return false;
}
return true;
}
void BFS(int x,int y){
queue<point>t;
Node.x=x,Node.y=y;
t.push(Node);
inq[x][y]=true;
while(!t.empty()){
point top=t.front();
t.pop();
for(int i=0;i<4;i++)
{
int newx=top.x+X[i];
int newy=top.y+Y[i];
if(judge(newx,newy)){
Node.x=newx;
Node.y=newy;
t.push(Node);
inq[newx][newy]=true;
}
}
}
}
int main(){
cin>>m>>n;
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
cin>>map[i][j];
}
}
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(map[i][j]==1&&inq[i][j]==false){
cut++;
BFS(i,j);
}
}
}
cout<<cut<<endl;
return 0;
}