AcWing 1076. 迷宫问题
原题链接
简单
#include <iostream>
#include <queue>
#include <cstring>
#include <sstream>
using namespace std;
const int nm = 1e3 + 50;
int n;
int g[nm][nm],st[nm][nm];
int dir[4][2] = {{0,1},{0,-1},{1,0},{-1,0}};
struct Node{
int x,y;
}f[nm][nm];
queue <Node> path;
void bfs()
{
string str;
string strx,stry;
queue <Node> q;
Node now,next;
now.x = 0;
now.y = 0;
st[0][0] = 1;
q.push(now);
while(q.size())
{
now = q.front();
if(now.x == n - 1&&now.y == n-1)
{
return;
}
for(int i = 0;i<4;i++)
{
next.x = now.x + dir[i][0];
next.y = now.y + dir[i][1];
int x = next.x,y = next.y;
if(x < 0||y<0||x>=n||y>=n) continue;
if(st[x][y] || g[x][y]) continue;
st[x][y] = 1;
q.push(next);
f[x][y] = now;//存储父节点
}
q.pop();
}
}
void dfs_print(int x,int y)//dfs从终点往前找
{
if(x == 0&&y == 0)//递归出口
{
return;
}
int prex = f[x][y].x,prey = f[x][y].y;//父结点
dfs_print(prex,prey);
cout << prex << " "<<prey <<"\n";
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin >> n;
for(int i = 0;i <n;i++)
for(int j = 0;j <n;j++)
cin >> g[i][j];
bfs();
dfs_print(n -1 ,n -1 );//递归查找父结点
cout <<n -1 << " " << n -1 ;
return 0;
}