题目描述
定义一个二维数组N*M(其中2<=N<=10;2<=M<=10),如5 × 5数组下所示:
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表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。入口点为[0,0],既第一空格是可以走的路。
Input
一个N × M的二维数组,表示一个迷宫。数据保证有唯一解,不考虑有多解的情况,即迷宫只有一条通道。
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)
输入描述:
输入两个整数,分别表示二位数组的行数,列数。再输入相应的数组,其中的1表示墙壁,0表示可以走的路。数据保证有唯一解,不考虑有多解的情况,即迷宫只有一条通道。
输出描述:
左上角到右下角的最短路径,格式如样例所示。
示例1
输入
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
输出
(0,0)
(1,0)
(2,0)
(2,1)
(2,2)
(2,3)
(2,4)
(3,4)
(4,4)
算法实现
#include <iostream>
#include <vector>
using namespace std;
void Fun(int cur_row, int cur_col, std::vector<std::vector<int>>& map, int row, int col, std::vector<std::pair<int, int>>& cur_path, std::vector<std::pair<int, int>>& closest_path)
{
if (cur_row >= row || cur_col >= col || map[cur_row][cur_col] == 1) return;
map[cur_row][cur_col] = 1;// 尝试走该点
cur_path.push_back(std::make_pair(cur_row, cur_col));
if (cur_row == row - 1 && cur_col == col - 1)// 递归结束条件,到达目的地
{
if (closest_path.empty() || cur_path.size() < closest_path.size())
{
closest_path = cur_path;
// 复原
map[cur_row][cur_col] = 0;
cur_path.pop_back();
return;
}
}
// 走其他方向
// 向右
if (cur_col + 1 < col && map[cur_row][cur_col + 1] != 1) Fun(cur_row, cur_col + 1, map, row, col, cur_path, closest_path);
// 向下
if (cur_row + 1 < row && map[cur_row + 1][cur_col] != 1) Fun(cur_row + 1, cur_col, map, row, col, cur_path, closest_path);
// 向左
if (cur_col - 1 >= 0 && map[cur_row][cur_col - 1] != 1) Fun(cur_row, cur_col - 1, map, row, col, cur_path, closest_path);
// 向上
if (cur_row - 1 >= 0 && map[cur_row - 1][cur_col] != 1) Fun(cur_row - 1, cur_col, map, row, col, cur_path, closest_path);
// 复原
map[cur_row][cur_col] = 0;
cur_path.pop_back();
}
int main()
{
int row, col;
while (std::cin >> row >> col)
{
std::vector<std::pair<int, int>> cur_path, closest_path; // 存储路径坐标
std::vector<std::vector<int>> map(row, std::vector<int>(col, 0));// 地图,0表示可走,1表示墙不可走 或者 已经走过了
for (int i = 0;i < row; ++i)
{
for (int j = 0; j < col; ++j)
{
std::cin >> map[i][j];
}
}
Fun(0, 0, map, row, col, cur_path, closest_path);
for (int i = 0; i < closest_path.size(); ++i)
{
cout << '(' << closest_path[i].first << ',' << closest_path[i].second << ')' << endl;//输出通路
}
}
return 0;
}