题目链接:https://cn.vjudge.net/contest/289570#status/jsu20164042033/H/0/
BFS求最短路,前驱数组pre记录搜索路径。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#include<vector>
#include<stack>
using namespace std;
struct node{
int x, y;
};
int arr[5][5];
int vis[5][5];
int dx[4] = {0, 1, -1, 0};
int dy[4] = {1, 0, 0, -1};
node pre[10][10];
void print(){
stack<node> st;
node k{4,4};
while(1){
st.push(k);
if(k.x==0&&k.y==0) break;
k = pre[k.x][k.y];
}
while(!st.empty()){
cout<<"("<<st.top().x<<", "<<st.top().y<<")"<<endl;
st.pop();
}
}
void bfs(int x, int y){
queue<node> q;
q.push(node{x, y});
vis[x][y] = true;
while(!q.empty()){
node tmp = q.front();
q.pop();
if(tmp.x==4&&tmp.y==4){
print();
return;
}
for(int i=0; i<4; i++){
int now_x = tmp.x + dx[i];
int now_y = tmp.y + dy[i];
if(0<=now_x && now_x<5 && 0<=now_y && now_y<5 && !vis[now_x][now_y] && arr[now_x][now_y]==0){
q.push(node{now_x, now_y});
pre[now_x][now_y] = tmp;
vis[now_x][now_y] = 1;
}
}
}
}
int main(){
for(int i=0; i<5; i++)
for(int j=0; j<5; j++)
cin>>arr[i][j];
memset(vis,0,sizeof(vis));
bfs(0, 0);
return 0;
}