Leetcode Problem 2642. Design Graph With Shortest Path Calculator
2642. Design Graph With Shortest Path Calculator
Leetcode Solutions
Dijkstra's Algorithm for Shortest Path in Directed Weighted Graph
Initialization: Create an adjacency list to represent the graph and initialize it with the given edges. Set the cost to reach each node from the source to infinity, except for the source node, which is set to 0.
Adding Edges: When a new edge is added, simply append it to the adjacency list of the source node.
Shortest Path Calculation: Use Dijkstra's algorithm to find the shortest path from the source to the destination. Maintain a priority queue to explore nodes with the lowest cost first. Update the cost for neighboring nodes if a cheaper path is found. Return the cost for the destination node if reachable, otherwise return -1.
Floyd–Warshall Algorithm for All Pairs Shortest Paths