[Google] LeetCode 1293 Shortest Path in a Grid with Obstacles Elimination 思维+BFS+贪心
You are given an m x n
integer matrix grid
where each cell is either \(0\) (empty) or \(1\) (obstacle). You can move up, down, left, or right from and to an empty cell in one step.
Return the minimum number of steps to walk from the upper left corner \((0, 0)\) to the lower right corner \((m - 1, n - 1)\) given that you can eliminate at most \(k\) obstacles. If it is not possible to find such walk return \(-1\).
Solution
需要从起点 \((0,0)\) 走到 \((m-1,n-1)\),且可以最多消去 \(k\) 个障碍。我们用 \(BFS\) 来解决,具体来说:由于一个位置可能有很多种访问方式,我们只需要贪心地保留所剩消除数目较多的路线即可
点击查看代码
class Solution {
private:
int dir[4][2] = {0,1, 1,0, 0,-1, -1,0};
int check(int x, int y, int r, int c){
if(x<0||y<0||x>=r||y>=c)return 0;
return 1;
}
public:
int shortestPath(vector<vector<int>>& grid, int k) {
queue<vector<int>> q;
int vis[41][41];
int r = grid.size(), c = grid[0].size();
for(int i=0;i<41;i++)
for(int j=0;j<41;j++)vis[i][j]=-1;
// x,y,path_length, #available remaining obstacles to remove
q.push({0,0,0,k});
while(!q.empty()){
auto a = q.front();
int x = a[0], y = a[1];
q.pop();
// arrive the target
if(x==r-1 && y==c-1)return a[2];
//if obstacle
if(grid[x][y]){
if(a[3]>0)a[3]--;
else continue;
}
// visited and remaining number of obstacles is more
if(vis[x][y]!=-1 && vis[x][y]>=a[3])continue;
vis[x][y] = a[3];
for(int i=0;i<4;i++){
int nx = x+dir[i][0], ny = y+dir[i][1];
if(check(nx,ny,r,c)){
q.push({nx,ny,a[2]+1,a[3]});
}
}
}
return -1;
}
};