您的位置:首页 > 其它

poj 3984 BFS

2016-05-12 00:30 246 查看
链接:戳这里

迷宫问题

Time Limit: 1000MS
Memory Limit: 65536K

Description

定义一个二维数组: 

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表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。

Input

一个5 × 5的二维数组,表示一个迷宫。数据保证有唯一解。

Output

左上角到右下角的最短路径,格式如样例所示。

Sample Input

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

Sample Output

(0, 0)

(1, 0)

(2, 0)

(2, 1)

(2, 2)

(2, 3)

(2, 4)

(3, 4)

(4, 4)

思路:bfs  在每次跑到一个新的未走的点时存下这个点的pre(从哪个点走过来的)  然后用二维组数存下这个点的pre值

代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<string>
#include<vector>
#include <ctime>
#include<queue>
#include<set>
#include<map>
#include<stack>
#include<iomanip>
#include<cmath>
#define mst(ss,b) memset((ss),(b),sizeof(ss))
#define maxn 0x3f3f3f3f
#define MAX 1000100
///#pragma comment(linker, "/STACK:102400000,102400000")
typedef long long ll;
typedef unsigned long long ull;
#define INF (1ll<<60)-1
using namespace std;
int a[10][10];
struct node{
int x,y,pre;
node(){}
node (int x,int y):x(x),y(y){}
};
int xx[4]={0,1,0,-1};
int yy[4]={1,0,-1,0};
bool pd(node t){
if(a[t.x][t.y]==1 || t.x<1 || t.x>5 || t.y<1 || t.y>5)
return false;
return true;
}
int anw[10][10];
void print(int pre){
if(pre>0){
int x,y;
if(pre%5==0) x=pre/5;
else x=pre/5+1;
y=pre%5;
if(y==0) y=5;
print(anw[x][y]);
printf("(%d, %d)\n",x-1,y-1);
}
}
void BFS(node S){
mst(anw,0);
queue<node> qu;
qu.push(S);
a[S.x][S.y]=1;
anw[S.x][S.y]=0;
while(!qu.empty()){
node now=qu.front(),next;
qu.pop();
for(int i=0;i<4;i++){
next.x=now.x+xx[i];
next.y=now.y+yy[i];
if(pd(next)){
a[next.x][next.y]=1;
next.pre=(now.x-1)*5+now.y;
anw[next.x][next.y]=next.pre;
///printf("%d %d %d\n",next.x,next.y,next.pre);
if(next.x==5 && next.y==5){
print(next.pre);
return ;
}
qu.push(next);
}
}
}
}
int main(){
int x;
while(scanf("%d",&x)!=EOF){
mst(a,0);
a[1][1]=x;
for(int i=1;i<=5;i++){
for(int j=1;j<=5;j++){
if(i==1 && j==1) continue;
scanf("%d",&a[i][j]);
}
}
node S=node(1,1);
BFS(S);
printf("(4, 4)\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: