AcWing 1076. 迷宫问题
原题链接
简单
作者:
hai阿卢
,
2021-03-07 22:51:12
,
所有人可见
,
阅读 254
#include<iostream>
#include<queue>
#include<vector>
using namespace std;
typedef pair<int, int> PII;
#define sx first
#define sy second
const int N = 1010;
int a[N][N], n;
PII rea[N][N];
bool s[N][N];
vector<PII> rep;
queue<PII> q;
void Bfs()
{
q.push({ 1, 1 });
int dx[4] = { -1, 0, 1, 0 }, dy[4] = { 0, 1, 0, -1 };
s[1][1] = true;
while (!q.empty())
{
PII it = q.front();
q.pop();
for (int i = 0; i < 4; i++)
{
int x = it.sx + dx[i];
int y = it.sy + dy[i];
if (x > 0 && x <= n && y > 0 && y <= n && a[x][y] == 0 && !s[x][y])
{
s[x][y] = true;
q.push({ x, y });
rea[x][y] = { it.sx, it.sy };
if(x == n && y == n) break;
}
}
}
int i = n, j = n;
int ii, jj;
for(int i = n, j = n;i != 0 || j != 0; i = rea[ii][jj].sx, j = rea[ii][jj].sy)
{
ii = i, jj = j;
rep.push_back({i, j});
}
}
int main()
{
cin >> n;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
cin >> a[i][j];
}
}
Bfs();
while(!rep.empty())
{
int x = rep.back().sx;
int y = rep.back().sy;
cout << x - 1 << " " << y - 1 << endl;
rep.pop_back();
}
return 0;
}