从队列到广度优先搜索 - 脑壳

1.STL中的queue

队列: 先进先出

#include <iostream>
#include <queue>
using namespace std;
int main(){
    queue <int> test;    // 定义: queue<typename> name;
    for (int i = 0; i < 5; ++i) {
        test.push(i);    //queue.push();将i加入队伍末尾; 队列内容:0 1 2 3 4
    }
    int head = test.front(),end = test.back();      //分别用queue.front(),queue.back()获取队列中开头和末尾的元素 head = 0,end = 4
    test.pop();     //pop(); 将队首元素移出; 此时队列内容:1 2 3 4
    cout<<test.size()<<endl;      //queue.size():返回队列中元素个数
    cout<<test.empty()<<endl;     //queue.empty():判断队列是否为空  false
}

注意:在使用front()pop()函数前,必须使用empty()判断队列是否为空,否则可能因为队列为空而出现错误。

2.广度优先搜索

依次访问根结点能直接到达所有节点,然后再按这些结点被访问的顺序去依次访问它们能够直接到达所有节点

void BFS(int s){
    queue<int> q;
    q.push(s);
    while(!q.empty()){
        取出队首元素top;
        访问队首元素top;
        将队首元素出队;
        将top的下一层结点中未曾入队的结点全部 大专栏  从队列到广度优先搜索 - 脑壳入队,并设置为已入队;
    }
}

3.例题

#include <cstdio>
#include <iostream>
#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){    //判断(x,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(){
    cin>>n>>m;
    for (int x = 0; x < n; ++x) {
        for (int y = 0; y < m; ++y) {
           cin>>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);
            }
        }
    }
    cout<<ans;
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/liuzhongrong/p/12407801.html