菜鸟什么时候才能变成老鸟,欢迎留言纠错~|

Shie1d

园龄:5年9个月粉丝:6关注:0

2642. 设计可以求最短路径的图类(中等)

核心思想
Dijkstra + 堆优化
模板题,每次查询做一次最短路查询即可。

class Graph {

    private List<int[]>[] nxt;

    public Graph(int n, int[][] edges) {
        nxt = new List[n];
        for(int i = 0; i < n; i++){
            nxt[i] = new ArrayList<>();
        }
        for(int[] edge: edges){
            int x = edge[0];
            int y = edge[1];
            int cost = edge[2];
            nxt[x].add(new int[]{y,cost});
        }
    }
    public void addEdge(int[] edge) {
        int x = edge[0];
        int y = edge[1];
        int cost = edge[2];
        nxt[x].add(new int[]{y,cost});
    }
    public int shortestPath(int node1, int node2) {
        int[] dis = new int[nxt.length];
        // o1 距离 o2 点
        PriorityQueue<int[]> pq = new PriorityQueue<int[]>((o1, o2) -> o1[0] - o2[0]);
        Arrays.fill(dis, Integer.MAX_VALUE);
        dis[node1] = 0;
        pq.add(new int[]{0, node1});
        while(!pq.isEmpty()){
            int[] edge = pq.poll();
            int x = edge[1];
            if(x == node2)
                return dis[x];
            for(int[] edgeTo: nxt[x]){
                int y = edgeTo[0];
                int cost = edgeTo[1];
                if(dis[y] > dis[x] + cost){
                    dis[y] = dis[x] + cost;
                    pq.add(new int[]{dis[y], y});
                }
            }
        }
        return -1;
    }
}

本文作者:ganyq

本文链接:https://www.cnblogs.com/ganyq/p/18109146

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   Shie1d  阅读(3)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起