struct Node
{
int x, y;
int rest; //还可以消几个障碍物
int dist; //距离
Node(int _x,int _y, int _rest, int _dist)
:x(_x), y(_y), rest(_rest),dist(_dist){}
};
class Solution {
static constexpr int dx[4] = {-1, 0, 1, 0}; //上右下左
static constexpr int dy[4] = { 0, 1, 0,-1};
public:
int shortestPath(vector<vector<int>>& grid, int k) {
int m = grid.size();
int n = grid[0].size();
if(n == 1 && m == 1)
{
return 0;
}
k = min(m + n -3, k);
bool visited[m][n][k+1];
memset(visited, false, sizeof(visited));
queue<Node>q;
q.push(Node(0,0,k,0)); // or q.emplace(0, 0, k, 0);
visited[0][0][k] = true;
while(!q.empty())
{
Node cur = q.front();
q.pop();
if(cur.x == m-1 && cur.y == n-1)
{
return cur.dist;
}
for(int i = 0; i < 4; i++)
{
int x = cur.x + dx[i];
int y = cur.y + dy[i];
if(x >= 0 && x < m && y >= 0 && y < n)
{
if(grid[x][y] == 0 && !visited[x][y][cur.rest])
{
q.emplace(x, y, cur.rest, cur.dist+1);
//or Node next(x, y, cur.rest, cur.dist+1);
//q.push(next);
visited[x][y][cur.rest] = true;
}
else if(grid[x][y] == 1 && cur.rest > 0
&& !visited[x][y][cur.rest-1])
{
q.emplace(x, y, cur.rest-1, cur.dist+1);
visited[x][y][cur.rest-1] = true;
}
}
}
}
return -1;
}
};
参考了题解:
https://leetcode-cn.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/solution/wang-ge-zhong-de-zui-duan-lu-jing-by-leetcode/