题目链接: 迷宫中离入口最近的出口
属于最短路径问题, 即求从给定位置走到终点的最短路径, 类似下图:
大致题解步骤:
1. 定义方向数组, 用于遍历某点的四周是否可以访问.
2. 定义一个与maze同行同列的二维数组, 用于判断某点是否已经访问过了.
3. 定义一个队列, 用于存储坐标
4. 做一次bfs, 每轮遍历需要遍历完当前层的所有元素, 每一层路径步数+1
5. 此题的出口定义为走到矩阵边界即可.
题解代码:
class Solution
{
public:
int nearestExit(vector<vector<char>>& maze, vector<int>& entrance)
{
int dx[4] = {0, 0, -1, 1};
int dy[4] = {1, -1, 0, 0};
int row = maze.size();
int col = maze[0].size();
vector<vector<bool>> vis(row, vector<bool>(col)); //判断某位置是否走过
vis[entrance[0]][entrance[1]] = true;
queue<pair<int, int>> q;
q.push({entrance[0],entrance[1]});
int res = 0; //记录到最近出口的最少步数
//bfs
while(q.size())
{
res++;
int n = q.size(); //记录当前层遍历个数
for(int k = 0; k < n; ++k)
{
auto [a, b] = q.front();
q.pop();
//遍历当前坐标四周哪个方向可以走
for(int i = 0; i < 4; ++i)
{
int x = a + dx[i];
int y = b + dy[i];
if(x >= 0 && x < row && y >= 0 && y < col && maze[x][y] == '.' && !vis[x][y])
{
//判断是否走到出口
if(x == 0 || x == row - 1 || y == 0 || y == col - 1)
{
return res;
}
vis[x][y] = true;
q.push({x, y});
}
}
}
}
return -1;
}
};