您的位置:首页 > 编程语言

POJ - 3984----迷宫问题

2017-02-04 13:45 246 查看
定义一个二维数组:

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,不过要记录路径同样的方法,每个节点多加个数组存储路径。

#include<iostream>
#include<cstring>
#include<queue>
#include<cstdio>
using namespace std;

int A[5][5];
bool visit[5][5];
int dx[4]={-1,0,0,1},dy[4]={0,1,-1,0};//走的四个方向

struct node{
int x,y;
int step;
char str[100][100];//记录步数
};

//得到此位置的情况
bool get(int x,int y){
if(x<5 && x>=0 && y<5 && y>=0 && !visit[x][y]){
return true;
}
return false;
}

int BFS(node start){
queue<node> Q;

Q.push(start);

while(!Q.empty()){
node tem = Q.front();
Q.pop();

if(tem.x==4 && tem.y==4){
for(int i=0 ; i<=tem.step ; i++){
cout<<tem.str[i]<<endl;
}
return 1;
}

for(int i=0 ; i<4 ; i++){
node temp=tem;
temp.x = tem.x+dx[i];
temp.y = tem.y+dy[i];

if(get(temp.x,temp.y)){
temp.step = tem.step+1;
visit[temp.x][temp.y] = true;
sprintf(temp.str[temp.step],"%s%d%s%d%s","(",temp.x,", ",temp.y,")");
Q.push(temp);
}
}
}
return 0;
}
int main(void){
memset(visit,false,sizeof(visit));
for(int i=0 ; i<5 ; i++){
for(int j=0 ; j<5 ; j++){
cin>>A[i][j];
if(A[i][j] == 1){
visit[i][j] = true;
}
}
}
node start;
start.x = 0;
start.y = 0;
start.step=0;
strcpy(start.str[start.step],"(0, 0)");
visit[start.x][start.y]=true;

BFS(start);

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  poj 编程 迷宫 BFS