迷宫问题
迷宫问题:给你一个而且只有一个出口的迷宫,你需要从入口出发,穿过迷宫,走到出口。要求找到最短路径。
#include <iostream>
#include <vector>
using namespace std;
// 给你二维矩阵,零代表可以走,一代表不可以走,从起点到终点,计算一下最短路径
// 思路:DFS
vector<string> path = {};
vector<string> min_path = {};
vector<tuple<int, int, char>> directions = {{0, 1, 'R'}, {1, 0, 'D'}, {0, -1, 'L'}, {-1, 0, 'U'}};
int start_x, start_y, end_x, end_y;
int min_length = INT_MAX;
// 检查坐标是否在矩阵内,是返回true,否则返回false
bool check(int x, int y, int w, int h)
{
if (x < 0 || x >= w || y < 0 || y >= h)
{
return false;
}
return true;
}
void printPath()
{
cout << "最短路径:" << endl;
for (auto p : min_path)
{
cout << p << " ";
}
}
void dfs(vector<vector<int>> &matrix, int w, int h, int x, int y, int current_length)
{
// 不能走到边界或者已经访问过
if (!check(x, y, w, h) || matrix[x][y] == 1)
{
return;
}
if (x == end_x && y == end_y)
{
if (current_length < min_length)
{
min_length = current_length;
min_path = path;
}
return;
}
matrix[x][y] = 1; // 标记为已访问
for (auto [dx, dy, direction] : directions)
{
int nx = x + dx, ny = y + dy;
path.push_back(string(1, direction));
dfs(matrix, w, h, nx, ny, current_length + 1);
path.pop_back();
}
matrix[x][y] = 0; // 回溯,标记为未访问
}
int test01()
{
int w, h;
cin >> w >> h;
// 读入矩阵
vector<vector<int>> matrix(h, vector<int>(w));
for (int i = 0; i < h; i++)
{
for (int j = 0; j < w; j++)
{
cin >> matrix[i][j];
}
}
cin >> start_x >> start_y >> end_x >> end_y;
// 开始DFS
dfs(matrix, w, h, start_x, start_y, 0);
if (min_length != INT_MAX)
{
cout << "找到终点" << endl;
cout << "最短路径长度为:" << min_length << endl;
}
else
{
cout << "没有找到终点" << endl;
}
printPath();
return 0;
}
详情可查看博客