总时间限制:
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)
这里不仅要求最短路径,还要记录路径,这里有个小技巧,先将地图的所有位置设为一个值,然后遍历的时候只有为0才能遍历,这样就可以不判断边界。
代码:
#include <iostream>
#include <vector>
#include <cstring>
using namespace std;
struct Pos
{
int r, c; // r为矩阵的行数,c为矩阵的列数
int father; // 父节点
int path; // 从起点到当前位置的步数
Pos(int rr = 0, int cc = 0, int ff = 0, int path_ = 0) :r(rr), c(cc), father(ff),path(path_){ }
};
int maze[8][8]; // 迷宫二维数组
Pos que[100]; // 队列
int head, tail; // 队列的头部和尾部
Pos dir[4] = { Pos(-1,0),Pos(1,0),Pos(0,-1),Pos(0,1) }; //移动方向
void BFS()
{
head = 0;
tail = 1;
que[0] = Pos(0, 0, -1);
while (head != tail)
{
Pos ps = que[head];
int r = ps.r, c = ps.c;
int path = ps.path;
// 如果走到终点,倒叙输出路径
if (ps.r == 4 && ps.c == 4)
{
cout << "经过的路径为 ";
cout << ps.path << endl;
vector<Pos> vt;
while (true)
{
vt.push_back(Pos(ps.r, ps.c, -2));
if (ps.father == -1)
break;
ps = que[ps.father];
};
// 倒叙输出
for (int i = vt.size() - 1; i >= 0; i--)
cout << "(" << vt[i].r << ", " << vt[i].c<< ")" << endl;
return;
}
// 广搜过程
for (int i = 0; i < 4; ++i)
if (!maze[r + dir[i].r][c + dir[i].c]) // 如果有路
{
que[tail++] = Pos(r + dir[i].r, c + dir[i].c,head, path+1); // 入队
maze[r + dir[i].r][c + dir[i].c] = 1; // 标记这条路走过
}
++head;
}
}
int main()
{
memset(maze, 0xff, sizeof(maze)); // 初始化迷宫数组
for (int i = 0; i < 5; i++) // 读入数据
for (int j = 0; j <5;j++)
cin >> maze[i][j];
BFS();
return 0;
}