查看: 1039| 回复: 0
跳转到指定楼层
上一主题 下一主题
收起左侧

[Leetcode] 505. The Maze II 复杂度

全局:

注册一亩三分地论坛,查看更多干货!

您需要 登录 才可以下载或查看附件。没有帐号?注册账号

x
本帖最后由 lovepxijun 于 2021-5-21 10:07 编辑

刷题小白 有些问题求教大神。
https://leetcode.com/problems/the-maze-ii/

1. 答案里面的BFS的complexity是不是不太对,我的个人感觉是 (m*n*m*n) worse case。答案里的complexity 也没有给任何的解释
2. 关于priority_queue 下的Dijkstra,我几乎是全抄的答案的JAVA implementation,我自己用的C++,但是却非常慢,不知道我是哪里搞错了,求教大家帮忙看看
3. 在Princeton 的Algorithm书里面的 Dijkstra eager version,用到了他们自己的可以改index的priority queue,这个在C++的standard library里面没有,面试的时候用Dijkstra是不是只能用我写的这种方式来实现了,有没有更好的?

BTW:其他贴子里的那种带color的code snippet怎么发出来的?

class Solution {
public:
    class compare {
    public:
        bool operator() (const vector<int>& a, const vector<int>& b) {
            return a[2] < b[2];
        }
    };   
    int shortestDistance(vector<vector<int>>& maze, vector<int>& start, vector<int>& destination) {
        int row = static_cast<int>(maze.size());
        int col = static_cast<int>(maze[0].size());
        const vector<vector<int>> neigh{{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
        vector<vector<int>> distance(row, vector<int>(col, INT_MAX));
        distance[start[0]][start[1]] = 0;

        // use Dijkstra's with min-value oriented priority queue, each element should be [x, y, distance], distance as the key
        priority_queue<vector<int>, vector<vector<int>>, compare> pq;
        pq.push({start[0], start[1], 0});
        while (!pq.empty()) {
            auto node = pq.top();
            pq.pop();
            if (distance[node[0]][node[1]] < node[2]) {
                continue;
            }
            for (const auto & dir: neigh) {
                int x = node[0] + dir[0];
                int y = node[1] + dir[1];
                int steps = 0;
                while (x >= 0 && x < row
                      && y >= 0 && y < col
                      && maze[x][y] == 0) {
                    steps++;
                    x += dir[0];
                    y += dir[1];
                }
                if (distance[x-dir[0]][y-dir[1]] > distance[node[0]][node[1]] + steps) {
                    distance[x-dir[0]][y-dir[1]] = node[2] + steps;
                    pq.push({x-dir[0], y-dir[1], distance[x-dir[0]][y-dir[1]]});
                }
            }
        }

        return distance[destination[0]][destination[1]] == INT_MAX ? -1: distance[destination[0]][destination[1]];
    }
};



上一篇:Python里面用什么数据结构代替TreeMap / OrderedMap
下一篇:大清早发现个Leetcode bug
您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表