AcWing 844. 走迷宫 BFS+路径输出代码
作者:
狐行千里
,
2022-03-26 19:37:06
,
所有人可见
,
阅读 206
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
typedef pair<int, int> PII;
const int N = 105;
int n, m, cnt;
int g[N][N], d[N][N];
PII pre[N][N], path[N*N];
void dfs()
{
queue<PII> q;
memset(d, -1, sizeof d);
d[0][0] = 0;
q.push({0, 0});
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
while(q.size())
{
auto t = q.front();
q.pop();
for(int i = 0; i < 4; i ++)
{
int x = t.first + dx[i], y = t.second + dy[i];
if(x >= 0 && x < n && y >= 0 && y < m && g[x][y] == 0 && d[x][y] == -1)
{
d[x][y] = d[t.first][t.second] + 1;
pre[x][y] = t;
q.push({x, y});
}
}
}
int x = n - 1, y = m - 1;
while(x || y)
{
path[cnt ++] = {x, y};
auto t = pre[x][y];
x = t.first, y = t.second;
}
}
int main()
{
cin >> n >> m;
for(int i = 0; i < n; i ++)
for(int j = 0; j < m; j ++)
cin >> g[i][j];
dfs();
cout << d[n - 1][m - 1] << endl;
for(int i = cnt; i >= 0; i --)
cout << path[i].first << " " << path[i].second << endl;
return 0;
}