广度优先搜索算法笔记例一

#include<iostream>
#include<queue>
#include<stdio.h>
using namespace std;
const int maxn=100;
struct node{
    int x,y;
}nodes;
int n,m;
int X[4]={0,0,1,-1};
int Y[4]={1,-1,0,0};
int matrix[maxn][maxn];
bool panduan[maxn][maxn]={false};
bool judge(int x,int y)
        {
                if(panduan[x][y]==true||matrix[x][y]==0)
                    return false;
                if(x<0||x>=n||y<0||y<=m)
                    return false;
            return true;
        }
void BFS(int x,int y)
        {
            queue<node>q;
            nodes.x=x;
            nodes.y=y;
            q.push(nodes);
            panduan[x][y]=1;
            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)) {
                        nodes.x = newx;
                        nodes.y = newy;
                        q.push(nodes);
                        panduan[newx][newy] = 1;
                    }
                }
            }

        };

int main()
{
    scanf("%d%d",n,m);
    for(int i=0;i<n;i++) {
        for (int j = 0; j < m; j++) {
            scanf("%d", &matrix[i][j]);

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

}

猜你喜欢

转载自blog.csdn.net/hhdmw/article/details/81192429