2642. Design Graph With Shortest Path Calculator

Difficulty:
Related Topics:
Similar Questions:

Problem

There is a directed weighted graph that consists of n nodes numbered from 0 to n - 1. The edges of the graph are initially represented by the given array edges where edges[i] = [fromi, toi, edgeCosti] meaning that there is an edge from fromi to toi with the cost edgeCosti.

Implement the Graph class:

Example 1:

Input
["Graph", "shortestPath", "shortestPath", "addEdge", "shortestPath"]
[[4, [[0, 2, 5], [0, 1, 2], [1, 2, 1], [3, 0, 3]]], [3, 2], [0, 3], [[1, 3, 4]], [0, 3]]
Output
[null, 6, -1, null, 6]

Explanation
Graph g = new Graph(4, [[0, 2, 5], [0, 1, 2], [1, 2, 1], [3, 0, 3]]);
g.shortestPath(3, 2); // return 6. The shortest path from 3 to 2 in the first diagram above is 3 -> 0 -> 1 -> 2 with a total cost of 3 + 2 + 1 = 6.
g.shortestPath(0, 3); // return -1. There is no path from 0 to 3.
g.addEdge([1, 3, 4]); // We add an edge from node 1 to node 3, and we get the second diagram above.
g.shortestPath(0, 3); // return 6. The shortest path from 0 to 3 now is 0 -> 1 -> 3 with a total cost of 2 + 4 = 6.

Constraints:

Solution (Java)

class Graph {
    List<List<int[]>> res;
    int n;
    public Graph(int n, int[][] edges) {
        this.n = n;
        res = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            res.add(new ArrayList<>());
        }
        for (int[] edge : edges) {
            int u = edge[0], v = edge[1], w = edge[2];
            res.get(u).add(new int[]{v, w});
        }
    }

    public void addEdge(int[] edge) {
        int u = edge[0], v = edge[1], w = edge[2];
        res.get(u).add(new int[]{v, w});
    }

    public int shortestPath(int node1, int node2) {
        PriorityQueue<int[]> nm = new PriorityQueue<>((a, b) -> a[1] - b[1]);
        nm.offer(new int[]{node1, 0});
        boolean[] visited = new boolean[n];
        while (!nm.isEmpty())
        {
            int[] curr = nm.poll();
            int u = curr[0], d = curr[1];
            if (visited[u])
            {
                continue;
            }
            visited[u] = true;
            if (u == node2) return d;
            for (int[] e : res.get(u))
            {
                int v = e[0], w = e[1];
                if (!visited[v])
                {
                    nm.offer(new int[]{v, d + w});
                }
            }
        }
        return -1;
    }
}

Explain:

nope.

Complexity: