迷宫问题 poj3984
查看 提交 统计 提问
总时间限制: 1000ms 内存限制: 65536kB
描述
定义一个二维数组:
int maze[5][5] = {
0, 1, 0, 0, 0,
0, 1, 0, 1, 0,
0, 0, 0, 0, 0,
0, 1, 1, 1, 0,
0, 0, 0, 1, 0,
};
它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。
输入
一个5 × 5的二维数组,表示一个迷宫。数据保证有唯一解。
输出
左上角到右下角的最短路径,格式如样例所示。
样例输入
0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0
样例输出
(0, 0)
(1, 0)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 4)
(4, 4)
这个题输出bfs走过的路径 ,怎么把走过的节点保存下来真的是一个问题,我也不知道怎么保存下来,在网上找了一个大神的代码 但是他的思路放在我的代码里面就出现问题了 不知道怎么修改 下面粘上大神的代码
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
int mp[5][5],vis[5][5];
int dir[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
struct node{
int x,y;
};
node pre[10][10];
void BFS(){
queue<node> que;
node str;
str.x=str.y=0;
que.push(str);
vis[0][0]=1;
while(!que.empty()){
node now = que.front();
que.pop();
if(now.x == 4 && now.y == 4)
return;
for(int i = 0;i < 4;i++){
node next;
next.x = now.x + dir[i][0];
next.y = now.y + dir[i][1];
if(next.x >= 0 && next.x < 5 && next.y >= 0 && next.y < 5 && !mp[next.x][next.y] && !vis[next.x][next.y]){
vis[next.x][next.y] = 1;
que.push(next);
pre[next.x][next.y] = now;
}
}
}
}
void print(node cur){
if(cur.x == 0 && cur.y == 0){
printf("(0, 0)\n");
return;
}
print(pre[cur.x][cur.y]); //逆序输出
printf("(%d, %d)\n",cur.x,cur.y);
}
int main(){
for(int i = 0;i < 5;i++){
for(int j = 0;j < 5;j++){
scanf("%d",&mp[i][j]);
}
}
BFS();
node ed;
ed.x = ed.y = 4;
print(ed);
return 0;
}
因为我觉得他的输出有点麻烦 也没有怎么看懂 我就自己看了写了一个简单的,有个问题是层次遍历 会把中心点周围的点全部输出来 ,不知道怎么解决把最小的路径的点存在队列中。
下面是我写的代码 结果错误
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <stack>
using namespace std;
int cross[5] = {0,0,-1,0,1};
int stra[5] = {0,1,0,-1,0};
int mapp[50][50];
bool vis[50][50];
stack <int> s1,s2;
struct node{
int x,y;
node(int a,int b){//构造方法
x = a;
y = b;
}
};
queue<node> q,q1;
void bfs(int x,int y){
q.push(node(x,y));
vis[x][y] = 1;
while(!q.empty()){
node now = q.front();
q.pop();
if(now.x == 4 && now.y == 4){
return;
}
for(int i = 1;i <= 4;i++){
int pre = now.x + cross[i];
int pry = now.y + stra[i];
if(mapp[pre][pry] != 1 && pry >=0 && pry < 5 && pre >= 0 && pre < 5){
vis[pre][pry] = 1;
q.push(node(pre,pry));
q1.push(now);
//s1.push(pre);s2.push(pry);ll
}
}
}
}
void print(){
while(!q1.empty()){
node a = q1.front();
q1.pop();
printf("(%d, %d)\n",a.x,a.y);
}
printf("(4, 4)\n");
}
int main(){
for(int i = 0;i < 5;i++){
for(int j = 0;j < 5;j++){
cin >> mapp[i][j];
}
}
memset(vis,0,sizeof(vis));
bfs(0,0);
print();
return 0;
}