[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 (empty) or (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 to the lower right corner given that you can eliminate at most obstacles. If it is not possible to find such walk return .
Solution
需要从起点 走到 ,且可以最多消去 个障碍。我们用 来解决,具体来说:由于一个位置可能有很多种访问方式,我们只需要贪心地保留所剩消除数目较多的路线即可
点击查看代码
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; } };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义