C++利用STL中的队列bfs一个0,1矩阵

该博客介绍了如何使用C++编程语言,结合STL中的队列(queue)数据结构,实现宽度优先搜索(BFS)来遍历一个0,1矩阵。博主首先定义了必要的数据结构,包括Node和Pot,然后定义了bfs函数进行搜索,同时考虑了边界条件和已访问节点的标记。最后,通过main函数输入矩阵并展示搜索路径的步数。" 139411715,4958065,YOLOv8优化:引入Gold层,"['目标检测', 'YOLO', '深度学习', '模型优化', 'ONNX']
摘要由CSDN通过智能技术生成
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;

const int maxn = 100;
bool visited[maxn][maxn];
int move[4][2]={{-1,0},{1,0},{0,-1},{0,1}};
int m, n;

struct Node
{
    int wall;
    int step;
};

struct Pot
{
    Pot(int x, int y):x(x),y(y){}
    int x;
    int y;
};

Node map[maxn][maxn];

void bfs(int x, int y)
{
    int steps = 0;
    queue<Pot> Q;
    Pot start(x, y);
    visited[x][y] = 1;
    map[x][y].step = steps;
    Q.push(start);
    int i;
    while(!Q.empty())
    {
        Pot now = Q.front();
        Q.pop();
        steps = map[now.x][now.y].step;
        for(i=0;i<4;i++)
        {
            int nx = now.x+move[i][0];
            int ny = now.y+move[i][1];
            if(nx>=0 && nx<m && ny>=0 && ny<n && !visited[nx][ny] && !map[nx][ny].wall)
            {
                Pot p(nx, ny);
                map[nx][ny].step = steps+1;
                Q.push(p);
                visited[nx][ny]=true;
            }
        }
    }
}

int main()
{
    memset(visited, false, sizeof(visited));
    cin>>m>>n;
    for(int i=0;i<m;i++)
        for(int j=0;j<n;j++)
            cin>>map[i][j].wall;
    bfs(0,0);
    for(int i=0;i<3;i++)
    {
        for(int j=0;j<3;j++)
            cout<<map[i][j].step<<" ";
        cout<<endl;
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值