题目链接:http://poj.org/problem?id=3984
迷宫问题
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) Source |
[Submit] [Go Back] [Status] [Discuss]
题目大意:略
解析:显然用BFS搜索,但本题要求输出路径,所以就要用模拟队列来记录路径,最后简单的递归输出路径
代码如下:
#include<iostream>
#include<algorithm>
#include<map>
#include<stack>
#include<queue>
#include<vector>
#include<set>
#include<string>
#include<cstdio>
#include<cstring>
#include<cctype>
#include<cmath>
#define N 4009
using namespace std;
const int inf = 1e9;
const int mod = 1<<30;
const double eps = 1e-8;
const double pi = acos(-1.0);
typedef long long LL;
int mp[6][6], vis[6][6];
int nx[6] = {-1, 0, 0, 1};
int ny[6] = {0, -1, 1, 0};
struct node
{
int x, y, s;
}t[N];
void Display(int r)
{
if(r == 0)
{
printf("(0, 0)\n"); return ;
}
Display(t[r].s);
printf("(%d, %d)\n", t[r].x - 1, t[r].y - 1);
}
void solve()
{
memset(vis, 0, sizeof(vis));
int i, x, y;
int s, e; s = e = 0;
vis[1][1] = 1;
t[s].x = t[s].y = 1; t[s].s = -1;
while(s <= e)
{
if(t[s].x == 5 && t[s].y == 5) break;
for(i = 0; i < 4; i++)
{
x = t[s].x + nx[i]; y = t[s].y + ny[i];
if(x < 1 || y < 1 || x > 5 || y > 5) continue;
if(vis[x][y] || mp[x][y]) continue;
t[++e].x = x; t[e].y = y; t[e].s = s;
vis[x][y] = 1;
}
s++;
}
Display(s);
}
int main()
{
int i, j;
for(i = 1; i <= 5; i++)
{
for(j = 1; j <= 5; j++)
scanf("%d", &mp[i][j]);
}
solve();
return 0;
}