#include <iostream>
#include <cstdio>
#include <string.h>
#include <queue>
using namespace std;
int v[10][10];
int cnt[10][10];// 记录走到这点的时间
int d[4][2] = {{-1,0},{1,0},{0,-1},{0,1}};
struct node{
int x,y;
node(){}
node(int xx,int yy){
x = xx,y = yy;
}
};
void bfs(){
queue<node> q;
q.push(node(1,1));
while(!q.empty()){
node temp = q.front();
q.pop();
for(int i = 0;i < 4;i++){
int a = temp.x + d[i][0], b = temp.y + d[i][1];
if(v[a][b]){
cnt[a][b] = cnt[temp.x][temp.y] + 1;
v[a][b] = 0;
q.push(node(a,b));
}
}
}
}
int ans[26][2];// 保存路径
int pri(){
ans[1][0] = 5,ans[1][1] = 5;
int cou = 1;
node now(5,5);
int flag = 1;
while(1){
flag = cou;
for(int i = 0;i < 4;i++){
int a = now.x + d[i][0], b = now.y + d[i][1];
if(cnt[a][b] != 0 && cnt[a][b] < cnt[now.x][now.y]){
ans[++cou][0] = a;
ans[cou][1] = b;
now.x = a,now.y = b;
break;
}
}
if(cou == flag){
break;
}
}
ans[++cou][0] = 1,ans[cou][1] = 1;
return cou;
}
int main()
{
int n = 5;
for(int i = 1;i <= n;i++){
for(int j = 1;j <= n;j++){
scanf("%d",&v[i][j]);
v[i][j] ^= 1;//1变0,0变1
}
}
v[1][1] = 0;
bfs();
int cou = pri();
for(int i = 0;i < cou;i++){
printf("(%d, %d)\n",ans[cou-i][0]-1,ans[cou-i][1]-1);
}
return 0;
}
poj 3984 迷宫问题(bfs 输出序列)
最新推荐文章于 2022-12-04 10:15:18 发布