2642. Design Graph With Shortest Path Calculator

Explanation

To solve this problem, we can use Dijkstra's algorithm to find the shortest path between two nodes in the graph. We will store the graph using an adjacency list and maintain a priority queue to keep track of the nodes with the minimum distance. We will also keep track of the minimum distance from the source node to each node in the graph.

  1. Initialize the distance array with infinity for all nodes except the source node which is set to 0.
  2. Create a priority queue and add the source node with distance 0 to it.
  3. While the priority queue is not empty, extract the node with the minimum distance.
  4. For each neighbor of the extracted node, update the distance if a shorter path is found and add the neighbor to the priority queue.
  5. Repeat the process until the priority queue is empty or the destination node is reached.
  6. Return the distance to the destination node if a path exists, otherwise return -1.

Time complexity:

  • The time complexity of Dijkstra's algorithm is O((V + E) log V) where V is the number of nodes and E is the number of edges in the graph.

Space complexity:

  • The space complexity is O(V) for storing the distances and O(V + E) for the adjacency list.
import java.util.*;

class Graph {
    Map<Integer, List<int[]>> adjList;
    
    public Graph(int n, int[][] edges) {
        adjList = new HashMap<>();
        for (int[] edge : edges) {
            adjList.computeIfAbsent(edge[0], k -> new ArrayList<>()).add(new int[]{edge[1], edge[2]});
        }
    }
    
    public void addEdge(int[] edge) {
        adjList.computeIfAbsent(edge[0], k -> new ArrayList<>()).add(new int[]{edge[1], edge[2]});
    }
    
    public int shortestPath(int node1, int node2) {
        PriorityQueue<int[]> pq = new PriorityQueue<>(Comparator.comparingInt(a -> a[1]));
        Map<Integer, Integer> distances = new HashMap<>();
        
        pq.offer(new int[]{node1, 0});
        distances.put(node1, 0);
        
        while (!pq.isEmpty()) {
            int[] curr = pq.poll();
            int node = curr[0];
            int dist = curr[1];
            
            if (node == node2) {
                return dist;
            }
            
            if (adjList.containsKey(node)) {
                for (int[] neighbor : adjList.get(node)) {
                    int nextNode = neighbor[0];
                    int weight = neighbor[1];
                    int newDist = dist + weight;
                    
                    if (!distances.containsKey(nextNode) || newDist < distances.get(nextNode)) {
                        distances.put(nextNode, newDist);
                        pq.offer(new int[]{nextNode, newDist});
                    }
                }
            }
        }
        
        return -1;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.