#include<cstdio>
#include<queue>
using namespace std;
const int maxn=100;
struct node{
int x,y;
}Node;//Node是一个node型的变量
int n,m;//矩阵大小为m*n
int matrix[maxn][maxn];//01矩阵
bool inq[maxn][maxn]={false};//记录位置(x,y)是否已入过队
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;
}
bfs练习题1
最新推荐文章于 2023-09-25 20:16:28 发布