定义一个二维数组:
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)
这是一个简单的广度优先搜索问题,在编写程序的过程中要注意边界
上代码:
#include<iostream> //广度优先搜索
#include<cstdio>
#include<cstring>
using namespace std;
int map[5][5];
int a[4] = { 1, -1, 0, 0 }; //方向
int b[4] = { 0, 0, -1, 1 };
struct stu //放坐标用的结构体数组
{
int row;
int column;
}coordinate[2000];
int pre[100];
int visit[10][10]; //路线标记管理 1是走过
//输出函数
void print(int x)
{
int t;
t = pre[x];
if (t == 0)
{
printf("(0, 0)\n");
printf("(%d, %d)\n", coordinate[x].row, coordinate[x].column);
return;
}
else
{
print(t);
printf("(%d, %d)\n", coordinate[x].row, coordinate[x].column);
}
}
void bfs()
{
int head,tail;
int x, y, x_, y_;
memset(visit, 0, sizeof(visit));
head = 0; tail = 1;
coordinate[0].row = 0;
coordinate[0].column= 0;
pre[0] = -1;
while (head < tail)
{
x = coordinate[head].row;
y = coordinate[head].column;
if (x == 4 && y == 4) //右下角结束
{
print(head);
return;
}
for (int i = 0; i < 5; i++)
{
x_ = x + a[i];
y_ = y + b[i];
if (visit[x_][y_] == 0 && x_ >= 0 && x_ <= 4 && y >= 0 && y <= 4 && map[x_][y_] == 0) //符合条件
{
visit[x_][y_] = 1; //标记
coordinate[tail].row = x_;
coordinate[tail].column = y_;
pre[tail] = head;
tail++;
}
}
head++;
}
return;
}
int main()
{
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
scanf("%d", &map[i][j]);
}
}
bfs();
return 0;
}