AcWing 1076. 迷宫问题
原题链接
简单
作者:
Value
,
2020-06-24 15:38:46
,
所有人可见
,
阅读 445
#include <iostream>
#include <queue>
#include <vector>
#include <algorithm>
using namespace std;
const int N = 1010;
int graph[N][N];
bool st[N][N];
int n;
typedef pair<int, int> pii;
int dic[4][2] = {
{0, -1}, {-1, 0}, {0, 1}, {1, 0}
};
pii pre[N][N];
void bfs(int x, int y){
queue<pii> qu;
vector<pii> route;
qu.push({x, y});
route.push_back({x, y});
st[x][y] = true;
while(!qu.empty()){
pii now = qu.front();
qu.pop();
for(int i = 0; i < 4; i ++ ){
int xx = now.first + dic[i][0];
int yy = now.second + dic[i][1];
if(xx < 0 || xx >= n || yy < 0 || yy >= n) continue;
if(st[xx][yy] || graph[xx][yy]) continue;
qu.push({xx, yy});
st[xx][yy] = true;
pre[xx][yy] = now;
}
}
}
int main(){
cin >> n;
for(int i = 0; i < n; i ++ ){
for(int j = 0; j < n; j ++ ){
cin >> graph[i][j];
}
}
bfs(0, 0);
vector<pii> route;
pii now = {n - 1, n - 1};
route.push_back(now);
while(true){
now = pre[now.first][now.second];
route.push_back(now);
if(now.first == 0 && now.second == 0) break;
}
reverse(route.begin(), route.end());
for(int i = 0; i < route.size(); i ++ ){
cout << route[i].first << " " << route[i].second << endl;
}
return 0;
}