zoukankan      html  css  js  c++  java
  • 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
    ",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;
    }
  • 相关阅读:
    获取网站IP地址(Linux,C)
    linux_c_udp_example
    linux_c_tcp_example
    golang-sort
    docker_jenkins
    依赖抽象,而不要依赖具体实现
    网络杂记
    游戏开发中遇到的问题
    随手杂记
    go多态
  • 原文地址:https://www.cnblogs.com/tianyudizhua/p/13476859.html
Copyright © 2011-2022 走看看