bugfree Icon
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course

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

  1. 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.
  2. Adding Edges: When a new edge is added, simply append it to the adjacency list of the source node.
  3. 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.
UML Thumbnail

Floyd–Warshall Algorithm for All Pairs Shortest Paths

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...