LeetCode 2290. Minimum Obstacle Removal to Reach Corner

🔗 https://leetcode.com/problems/minimum-obstacle-removal-to-reach-corner

题目

  • 给 m * n 的二维数组,0 代表空 cell,1 代表有障碍物
  • 从 0,0 到 m-1,n-1,需要至少移掉几个障碍物
  • 格子间的路径只能是上下左右

思路

  • 第一反应是 dfs + 剪枝,后来想着还没正儿八经写过 dijkstra,试一下 dijkstra
  • 对 cell 进行编码,从二维降为一维度,[row_index, col_index]→ row_index * col_num + col_index
  • 定义一个最小堆,记录当前 cell 的编号,以及起始 cell 到当前 cell 的最短距离 len,用堆顶扩展可触达的 cell
    • 如果到了目的地,返回 len,
    • 如果没到达过,更新 len,如果该 cell 是障碍物, len+1,入堆
    • 如果到达过,且历史到达的 distance 比当前到达的大,重新入堆

代码

cpp 复制代码
class Solution {
public:
    int minimumObstacles(vector<vector<int>>& grid) {
               auto minHeapCompare = [](pair<int, int> left, pair<int, int> right) {
            return left.second > right.second; // 自定义比较器,建立最小堆
        };
        std::priority_queue<pair<int, int>, std::vector<pair<int, int>>,
                            decltype(minHeapCompare)>
            heap(minHeapCompare);

        int m = grid.size(), n = grid[0].size();
        int goal = m * n - 1;
        vector<int> visit(goal + 1, -1);
        visit[0] = 0;
        // init node
        int dst = 0, len = 0;
        pair<int, int> path;
        path = make_pair(dst, len);
        heap.push(path);
        vector<vector<int>> dir = {{-1, 0}, {0, -1}, {1, 0}, {0, 1}};
        // dijkstra
        while (heap.empty() == false) {
            path = heap.top();
            heap.pop();
            dst = path.first, len = path.second;
            if (dst == goal) return len;
            if (visit[dst] != -1 && visit[dst] < len) continue;
            for (int i = 0; i < dir.size(); i++) {
                int row = dst / n, col = dst % n;
                row += dir[i][0]; col += dir[i][1];
                if (row >= m || row < 0 || col >= n || col < 0) continue;
                int new_dst = row * n + col;
                int new_len = len;
                if (grid[row][col]) new_len++;
                if (visit[new_dst] == -1 || visit[new_dst] > new_len) {
                    visit[new_dst] = new_len;
                    path = make_pair(new_dst, new_len);
                    heap.push(path);
                }                
            }
        }
        return 0;
    }
};
相关推荐
黑听人5 小时前
【力扣 困难 C】329. 矩阵中的最长递增路径
c语言·leetcode
YuTaoShao7 小时前
【LeetCode 热题 100】141. 环形链表——快慢指针
java·算法·leetcode·链表
小小小新人121238 小时前
C语言 ATM (4)
c语言·开发语言·算法
你的冰西瓜9 小时前
C++排序算法全解析(加强版)
c++·算法·排序算法
এ᭄画画的北北9 小时前
力扣-31.下一个排列
算法·leetcode
绝无仅有10 小时前
企微审批对接错误与解决方案
后端·算法·架构
用户50408278583910 小时前
1. RAG 权威指南:从本地实现到生产级优化的全面实践
算法
Python×CATIA工业智造12 小时前
详细页智能解析算法:洞悉海量页面数据的核心技术
爬虫·算法·pycharm
Swift社区12 小时前
Swift 解 LeetCode 321:拼接两个数组中的最大数,贪心 + 合并全解析
开发语言·leetcode·swift