BFS

BFS

算法思想:

通过队(STL容器queue)/栈(STL容器stack)的使用,实现对全地图的检索
不同与dfs的单向检索,bfs是将所有路径同时进行检索

浅谈队(queue) --> 先进后出

浅谈栈(stack) --> 后进先出

算法实现:

在BFS中不再使用递归来实现遍历,而是通过判断将所的路径导入队/栈中,通过队/栈的使用去实现全图的遍历
将推入队/栈的数据进行标记,防止重复遍历
要求,对队/栈的使用要有基本的了解

例题:

/*
*迷宫问题

  • 一人处于(1,1)点上,‘1’是墙壁‘0’是路
  • 只能上下左右移动
  • 问从(1,1)到右下角的出口至少要移动多少次

样例输入
5 5
0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0
*/

ACODE

#include <bits/stdc++.h>

#define ll long long
#define endl '\n'
using namespace std;

int dx[4] = {1,-1,0,0};
int dy[4] = {0,0,1,-1};
int TY[105][105],vis[105][105],dis[105][105];
#define PII pair<int , int>
int n,m;
int bfs(){
    queue<PII> q;
    q.push({1,1});  //将起点推入队列里
    vis[1][1] = true;       //将起点标记成已经走过
    dis[1][1] = 0;          //走了几步

    while (q.size()){
        auto ty = q.front();
        q.pop();
        int x = ty.first, y = ty.second;
        for (int i = 0; i < 4; i++) {
            int xx = x + dx[i],yy = y + dy[i];
            if(xx < 1 || xx > n || yy < 1 || yy > m)continue;
            if(TY[xx][yy])continue;
            if(vis[xx][yy])continue;

            q.push({xx,yy});
            vis[xx][yy] = true;             //将可以走的点标记
            dis[xx][yy] = dis[x][y] + 1;    //记录
        }
    }
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= m; j++) {
            cout << dis[i][j] << " ";
        }
        cout << endl;
    }
    return dis[n][m];
}
int main() {
    ios::sync_with_stdio(0);
    cin.tie(0), cout.tie(0);
    cin >> n >> m;
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= m; j++) {
            cin >> TY[i][j];
        }
    }
    cout << endl;
    cout << bfs();
    return 0;
}
posted @ 2023-03-21 14:19  TFOREVERY  阅读(36)  评论(0编辑  收藏  举报