返回顶部

BFS计算块

#include<iostream>
#include<cstdio>
#include<queue>

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>=m||x<0||y>=n||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",&m,&n);

    for(int i=0; i<m; i++) {
        for(int j=0; j<n; j++) {
            scanf("%d",&matrix[i][j]);
        }
    }
    int ans=0;
    for(int i=0; i<m; i++) {
        for(int j=0; j<n; j++) {
            if(matrix[i][j]==1&&inq[i][j]==false) {
                ans++;
                BFS(i,j);
            }
        }
    }
    printf("%d\n",ans);

7 6
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
    return 0;
}

 

posted @ 2020-08-11 17:10  tianyudizhua  阅读(135)  评论(0编辑  收藏  举报