迷宫问题
定义一个二维数组:
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<algorithm>
#include<queue>
#include<cstring>
using namespace std;
struct pos {
int x;
int y;
};
int room[10][10];
pos f[10][10];
int dir_x[4] = { 0,1,0,-1 };
int dir_y[4] = { -1,0,1,0 };
void print(int x, int y)
{
if (x == 1 && y == 1)
{
cout << "(0, 0)" << endl;
return;
}
print(f[x][y].x, f[x][y].y);
cout << "(" << x - 1 << ", " << y - 1 << ")" << endl;
}
void bfs(int x, int y)
{
queue<pos> q;
int cnt = 2;
q.push({ x,y });
while (!q.empty())
{
pos start = q.front();
q.pop();
room[start.x][start.y] = cnt++;
for (int i = 0; i < 4; i++)
{
int a = start.x + dir_x[i];
int b = start.y + dir_y[i];
if (room[a][b] == 0)
{
f[a][b] = start;
q.push({ a,b });
}
}
}
}
int main()
{
memset(room, 1, sizeof(room));
for (int i = 1; i <= 5; i++)
for (int j = 1; j <= 5; j++)
cin >> room[i][j];
bfs(1, 1);
print(5, 5);
return 0;
}