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;
    }
};
相关推荐
木井巳8 小时前
【递归算法】二叉搜索树中第K小的元素
java·算法·leetcode·深度优先·剪枝
铉铉这波能秀8 小时前
LeetCode Hot100 中 enumerate 函数的妙用(2026.2月版)
数据结构·python·算法·leetcode·职场和发展·开发
墨有6668 小时前
哈希表从入门到实现,一篇吃透!
数据结构·算法·哈希算法
We་ct8 小时前
LeetCode 228. 汇总区间:解题思路+代码详解
前端·算法·leetcode·typescript
AIpanda8888 小时前
如何借助AI销冠系统提升数字员工在销售中的成效?
算法
啊阿狸不会拉杆8 小时前
《机器学习导论》第 7 章-聚类
数据结构·人工智能·python·算法·机器学习·数据挖掘·聚类
木非哲9 小时前
机器学习--从“三个臭皮匠”到 XGBoost:揭秘 Boosting 算法的“填坑”艺术
算法·机器学习·boosting
Re.不晚9 小时前
JAVA进阶之路——数据结构之线性表(顺序表、链表)
java·数据结构·链表
小辉同志9 小时前
437. 路径总和 III
算法·深度优先·广度优先
笨笨阿库娅9 小时前
从零开始的算法基础学习
学习·算法