Dijkstra: Shortest Reach 2

  • + 0 comments

    js

    function shortestReach(n, edges, s) {
        const graph = {};
        for (let i = 1; i <= n; i++) {
            graph[i] = {};
        }
        for (const [begin, end, weight] of edges) {
            if ((graph[begin][end] ?? Infinity) < weight) continue;
            graph[begin][end] = weight;
            graph[end][begin] = weight;
        }
    
        const result = {};
        const distance = { [s]: 0 };
        const candidates = new Set([s]);
        while (candidates.size) {
            let nextShortest;
            let minDis = Infinity;
            for (const c of candidates) {
                if (distance[c] < minDis) {
                    nextShortest = c;
                    minDis = distance[c];
                }
            }
            result[nextShortest] = minDis;
            candidates.delete(nextShortest);
    
            for (const [node, dis] of Object.entries(graph[nextShortest])) {
                if (result[node] !== undefined) continue;
    
                distance[node] = Math.min(
                    distance[node] ?? Infinity,
                    minDis + dis
                );
                candidates.add(node);
            }
        }
    
        const ret = [];
        for (let i = 1; i <= n; i++) {
            if (i === s) continue;
            ret.push(result[i] ?? -1);
        }
        return ret;
    }