迷宫问题
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 36134 | Accepted: 20444 |
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)
Source
在迷宫上找最短路径,就是经典的广度优先算法问题,这题难得地方在于给出路径,如果不要给出路径,则可用下面代码解决,注意代码中四个方向遍历的实现方法
#include<iostream>
#include<queue>
using namespace std;
bool visited[5][5]; // 查看地图是否被访问
int map[5][5]; // 标记地图
int dx[4] = { 0,1,0,-1 }; // x方向移动路径
int dy[4] = { 1,0,-1,0 };
struct Node
{
int x;
int y;
int s; // 起点到当前点的最短路径
};
bool judge(int x, int y)
{
if (x < 0 || x>5 || y < 0 || y >= 5)
return true;
if (visited[x][y])
return true;
if (map[x][y])
return true;
return false;
}
Node bfs()
{
queue<Node> q;
Node cur, next;
int nx, ny;
cur.x = 0;
cur.y = 0;
cur.s = 0;
visited[0][0] = true;
q.push(cur);
while (!q.empty())
{
cur = q.front();
q.pop();
if (cur.x == 4 && cur.y == 4)
return cur;
for (int i = 0; i < 4; i++)
{
// 四种遍历方法
nx = cur.x + dx[i];
ny = cur.y + dy[i];
if (judge(nx, ny))
{
// 如果这种走法不行,尝试下一种走法
continue;
}
// 可以走
next.x = nx;
next.y = ny;
next.s = cur.s + 1;
q.push(next);
}
}
return cur;
}
int main()
{
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
scanf_s("%d", &map[i][j]);
}
}
memset(visited, 0, sizeof(visited));
Node ans = bfs();
printf("%d\n", ans.s);
}