Description
定义一个二维数组:
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一次计算出每个点到终点的最短距离,再从起点BFS出到终点的最短路,这条路上每一个点到终点的最短距离依次减少1。
思考:
1、一定要先判断可不可以压入队列再往队列里压。
2、
#include <iostream>
#include <cstdio>
#include <string>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <vector>
#include <map>
#include <set>
#include <queue>
using namespace std;
struct point{
int x, y;
point(int xx, int yy) : x(xx), y(yy) {};
};
int maze[6][6], dir[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}, vis[6][6], len[6][6];
void BFS()
{
queue<point> q;
q.push (point (4, 4));
vis[4][4] = 1;
len[4][4] = 0;
while (!q.empty()) {
point now(0, 0);
now = q.front(); q.pop();
for (int i = 0; i < 4; i++) {
int tempx = now.x + dir[i][0];
int tempy = now.y + dir[i][1];
if (tempx > 4 || tempx < 0 || tempy > 4 || tempy < 0 || vis[tempx][tempy] || maze[tempx][tempy] == 1) continue;
vis[tempx][tempy] = 1;
len[tempx][tempy] = len[now.x][now.y] + 1;
if (tempx == 0 && tempy == 0) break;
q.push(point(tempx, tempy));
}
}
}
void print()
{
memset (vis, 0, sizeof(vis));
queue<point> q;
q.push (point (0, 0));
vis[0][0] = 1;
printf ("(0, 0)\n");
while (!q.empty()) {
point now(0, 0);
now = q.front(); q.pop();
for (int i = 0; i < 4; i++) {
int tempx = now.x + dir[i][0];
int tempy = now.y + dir[i][1];
if (tempx > 4 || tempx < 0 || tempy > 4 || tempy < 0 || vis[tempx][tempy] || maze[tempx][tempy] == 1 || len[tempx][tempy] != len[now.x][now.y] - 1) continue;
vis[tempx][tempy] = 1;
printf ("(%d, %d)\n", tempx, tempy);
if (tempx == 4 && tempy == 4) break;
q.push(point(tempx, tempy));
}
}
}
int main()
{
#ifndef ONLINE_JUDGE
freopen ("in.txt", "r", stdin);
#endif // ONLINE_JUDGE
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
scanf ("%d", &maze[i][j]);
len[i][j] = -1;
}
}
memset (vis, 0, sizeof(vis));
BFS ();
print ();
return 0;
}