B12 BFS 迷宫 最短路

视频链接:113 迷宫 最短路_哔哩哔哩_bilibili

POJ3984 迷宫问题

#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;

const int N = 1010;
int n,g[N][N];
struct Node{
  int x,y;
} path[N][N];
int dx[4]={-1,0,1,0};
int dy[4]={0,1,0,-1};

void bfs (int x,int y){
  queue<Node> q;
  q.push({x,y});
  g[x][y] = 1;
  while(q.size()){
    auto u=q.front(); q.pop();
    for(int i = 0; i < 4; i ++){
      int a = u.x+dx[i],b = u.y+dy[i];
      if(a<0||a>=n||b<0||b>=n)continue;
      if(g[a][b])continue;
      g[a][b] = 1;
      path[a][b] = u;
      q.push({a,b});
    }        
  }
}
int main(){
  cin >> n;
  for(int i = 0; i < n; i ++)
    for(int j = 0; j < n; j ++)
      scanf("%d",&g[i][j]);
  bfs(n-1,n-1); //倒序搜索
  Node p={0,0};
  while(1){
    printf("%d %d\n",p.x,p.y);
    if(p.x==n-1&&p.y==n-1)break;
    p = path[p.x][p.y];
  }
  return 0;
}

 

posted @ 2022-05-28 13:20  董晓  阅读(665)  评论(0编辑  收藏  举报