题目描述:
给出一个m*n的矩阵,矩阵中的元素为0或1.称位置(x,y)与其上下左右四个位置是相邻的。如果矩阵中有若干个1相邻,则称这些1构成了一个块。求给定矩阵中的块数。
输入:
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 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<queue>
#include<cstdio>
using namespace std;
const int maxn=100;
struct node{
int x,y;
} Node;
int n,m;
int matrix[maxn][maxn];
bool inq[maxn][maxn]={false};
int X[4]={0,0,1,-1};
int Y[4]={1,-1,0,0};
bool judge(int x,int y)
{
if(x>=n||x<0||y>=m||y<0)
return false;
if(matrix[x][y]==0||inq[x][y]==true)
return false;
return true;
}
void BFS(int x,int y)
{
queue<node> Q;
Node.x=x;
Node.y=y;
Q.push(Node);
inq[x][y]=true;
while(!Q.empty())
{
node top=Q.front();
Q.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;
Q.push(Node);
inq[newx][newy]=true;
}
}
}
}
int main()
{
scanf("%d%d",&n,&m);
for(int x=0;x<n;x++)
{
for(int y=0;y<m;y++)
{
scanf("%d",&matrix[x][y]);
}
}
int ans=0;
for(int x=0;x<n;x++)
{
for(int y=0;y<m;y++)
{
if(matrix[x][y]==1&&inq[x][y]==false)
{
ans++;
BFS(x,y);
}
}
}
printf("%d\n",ans);
return 0;
}