定义一个二维数组:
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问题,详细分析过程昝略
AC代码:
#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
int main()
{
queue<int>q;
int i, j, x, y;
int dx[4] = { 0,1,-1,0 }, dy[4] = { 1,0,0,-1 }, vis[5][5], map[5][5];
char ch[5][5];
for (i = 0; i < 5; i++)
for (j = 0; j < 5; j++)
cin >> ch[i][j];
int sx = 0, sy = 0;
q.push(4);
q.push(4);
memset(vis, 0, sizeof(vis));
memset(map, 0, sizeof(map));
while (q.size())
{
sx = q.front(); q.pop();
sy = q.front(); q.pop();
if (sx == 0 && sy == 0) break;
for (i = 0; i < 4; i++)
{
x = sx + dx[i];
y = sy + dy[i];
if (!vis[x][y] && ch[x][y] == '0'&&x >= 0 && x < 5 && y >= 0 && y < 5)
{
q.push(x);
q.push(y);
vis[x][y] = 1;
map[x][y] = map[sx][sy] + 1;
}
}
}
sx = 0; sy = 0;
cout << "(0, 0)" << endl;
int k = 0;
while (k != map[0][0] - 1)
{
for (i = 0; i < 3; i++)
{
x = sx + dx[i];
y = sy + dy[i];
if (map[x][y] == map[sx][sy] - 1)
{
cout << '(' << x << ", " << y << ')' << endl;
k++;
break;
}
}
sx = x; sy = y;
}
cout << "(4, 4)" << endl;
return 0;
}