2642. Design Graph With Shortest Path Calculator

T: Graph: O(E+V), addEdge: O(N) N times add edge, shortestPath: O(M* (V+ ElogV)), M times shortestPath, Arrays.fill (V) , dijisktra: O(ElogV)
S: O(E+V+N) , N times addEdge, so add N space
```java
class Graph {
    class Node {
        int id;
        int cost;
        Node(int id, int cost) {
            this.id = id;
            this.cost = cost;
        }
    }
    private Map<Integer, List<Node>> graph;
    private int n;
    public Graph(int n, int[][] edges) {
        this.n = n;
        this.graph = new HashMap<>();
        for (int[] edge : edges) {
            graph.putIfAbsent(edge[0], new ArrayList<>());
            graph.get(edge[0]).add(new Node(edge[1], edge[2]));
        }
    }
    
    public void addEdge(int[] edge) {
        graph.putIfAbsent(edge[0], new ArrayList<>());
        graph.get(edge[0]).add(new Node(edge[1], edge[2]));
    }
    
    public int shortestPath(int node1, int node2) {
        Queue<Node> pq = new PriorityQueue<>((a,b) -> a.cost - b.cost);
        pq.offer(new Node(node1, 0));
        boolean[] visited = new boolean[n];
        int[] currentCost = new int[n];
        Arrays.fill(currentCost, Integer.MAX_VALUE); // because we want smaller one!

        while (!pq.isEmpty()) {
            Node cur = pq.poll();
            if (visited[cur.id]) {
                continue;
            }
            visited[cur.id] = true;
            currentCost[cur.id] = cur.cost;
            if (cur.id == node2) {
                return cur.cost; 
            }
            if (graph.containsKey(cur.id)) {
                for (Node next : graph.get(cur.id)) {
                    int newCost = cur.cost + next.cost;
                    if (newCost < currentCost[next.id]) {
                        pq.offer(new Node(next.id, newCost));
                    }
                }
            }
        }
        return -1;
    }
}

/**
 * Your Graph object will be instantiated and called as such:
 * Graph obj = new Graph(n, edges);
 * obj.addEdge(edge);
 * int param_2 = obj.shortestPath(node1,node2);


 T: Graph: O(E+V), addEdge: O(N) N times add edge, shortestPath: O(M* (V+ ElogV)), M times shortestPath, Arrays.fill (V) , dijisktra: O(ElogV)
 S: O(E+V+N) , N times addEdge, so add N space
 */
```

Last updated