10:迷宫问题
点击打开链接
http://bailian.openjudge.cn/2016acm/10/
总时间限制:
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)
解题思路:
利用结构体储存当前的坐标x,y和该点的前驱和本身pre,n;本题利用广度搜索向每个可走的方向(这里是四个方向,有的是八个方向)走一步,并记录该点的坐标前驱和本身,最后返回一个终点的本身(n,代表广搜的第n个点),然后利用递归输出前驱坐标。
代码实现:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <map>
#include <vector>
#include <set>
#include <cmath>
#include <algorithm>
using namespace std;
const int maxn = 30;
int mp[5][5]; // 地图;
int vis[5][5]={0}; // 标记走过与否;
int dis[4][2] = { {0,1}, {0,-1}, {1,0}, {-1,0} }; // 可走的四个方向;
struct node //记录该点的信息;
{
int x, y, pre, n;
}point[maxn];
int bfs()
{
point[0] = { 0, 0, -1, 0 };
int cnt=0;
queue<node>q;
q.push( point[0] );
vis[0][0] = 1;
while( !q.empty() )
{
node t = q.front();
q.pop(); // 每次取队列第一个元素并释放;
int nowx = t.x, nowy = t.y, now = t.n;
if( nowx == 4 && nowy == 4)
return now;
for( int i=0; i<4; i++ ) // 四个方向各走一次;
{
int gx = nowx + dis[i][0], gy = nowy + dis[i][1];
if( gx >= 0 && gx < 5 && gy >= 0 && gy < 5 && !vis[gx][gy] && !mp[gx][gy])
{
point[++cnt] = { gx, gy, now, cnt};
vis[gx][gy] = 1; // 标记该点走过;
q.push(point[cnt]); // 将每次去得元素的可走路压入队列;
}
}
}
}
void dfs( int d )
{
if( point[d].n )
dfs( point[d].pre ); // 利用递归找到起点,依次递归输出;
printf("(%d, %d)\n" , point[d].x, point[d].y );
}
int main()
{
int i, j;
for( i=0; i<5; i++ )
for( j=0; j<5; j++ )
cin >> mp[i][j];
int m =bfs();
dfs(m);
return 0;
}