POJ 3984迷宫问题 (BFS做法)

来源:互联网 发布:seo超级伪静态 编辑:程序博客网 时间:2024/06/05 07:23

迷宫问题
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 23715 Accepted: 13817

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 00 1 0 1 00 0 0 0 00 1 1 1 00 0 0 1 0

Sample Output

(0, 0)(1, 0)(2, 0)(2, 1)(2, 2)(2, 3)(2, 4)(3, 4)(4, 4)
这道题,题意很明显,难点就在于这个路径怎么保存。

其实直接放在结构体里就好了。

#include<cstdio>#include<cstring>#include<iostream>#include<algorithm>#include<queue>using namespace std;int maze[10][10];struct path{int x;int y;int i;int x1[30];//存放路径int y1[30];//存放路径};int main(){for (int i = 0; i < 10; i++)//初始化地图全部为墙{for (int j = 0; j < 10; j++)maze[i][j] = 1;}for (int i = 1; i <= 5; i++)//输入数据  从1开始输入 不用管边界  边界为墙了{for (int j = 1; j <= 5; j++){cin >> maze[i][j];}}queue<path>q;//初始化队列  bfspath start;start.i = 0;start.x = 1;start.y = 1;start.x1[0] = 1;start.y1[0] = 1;q.push(start);while (!q.empty()){if (q.front().x == 5 && q.front().y == 5)break;//找到结束if (maze[q.front().x][q.front().y + 1] == 0)//能横着走{path temp=q.front();      //必须重新设置个临时对象 否则会将原来的值给覆盖掉temp.i++;temp.y++;temp.x1[temp.i] = q.front().x;temp.y1[temp.i] = q.front().y + 1;q.push(temp);}if (maze[q.front().x + 1][q.front().y] == 0)//能竖着走{path temp=q.front();temp.i++;temp.x ++;temp.y = q.front().y;temp.x1[temp.i] = q.front().x + 1;temp.y1[temp.i] = q.front().y;q.push(temp);}maze[q.front().x][q.front().y] = 1;//走过设置为墙 防止重复走 这里可以不用q.pop();}for (int i = 0; i <= q.front().i; i++)//输出结果{cout << "(" << q.front().x1[i] - 1 << ", " << q.front().y1[i] - 1 << ")" << endl;}return 0;}