xinyu04

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

[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 (m1,n1) given that you can eliminate at most k obstacles. If it is not possible to find such walk return 1.

Solution

需要从起点 (0,0) 走到 (m1,n1),且可以最多消去 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;
}
};

posted on   Blackzxy  阅读(20)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
点击右上角即可分享
微信分享提示