Dijkstra's algorithm

Graphs Shortest Path Algorithms Hard
  • The concept underlying this programming problem is used in the implementation of various routing algorithms in major navigation applications like Google Maps or Waze
  • For example, Dijkstra’s algorithm, which also finds the shortest path given a source node in a graph (which could represent cities, intersections etc
  • ) with associated weights (distances, time or cost), enables these apps to provide users with the quickest or shortest route to their destination
  • This problem is fundamental to the field of Graph Theory that lays the foundation for network analysis and optimization in various domains including computer networks, operations research, and transportation

Given a weighted, undirected graph of V vertices, numbered from 0 to V-1, and an adjacency list adj where adj[i] is a list of lists containing two integers where the first integer of each list j denotes there is edge between i and j , second integers corresponds to the weight of that edge . 


Given a source node S. Find the shortest distance of all the vertex from the source vertex S. Return a list of integers denoting shortest distance between each node and source vertex S. If a vertex is not reachable from source then its distance will be 109.

Examples:


Input: V = 2, adj [] = [[[1, 9]], [[0, 9]]], S=0

Output: [0, 9]

Explanation: The shortest distance from node 0(source) to node 0 is 0 and the shortest distance from node 0 to node 1 is 6.


Input: V = 3,adj = [[[1, 1], [2, 6]], [[2, 3], [0, 1]], [[1, 3], [0, 6]]], S=2

Output: [4, 3, 0]

Explanation: 

For node 0, the shortest path is 2->1->0 (distance=4)

For node 1, the shortest path is 2->1 (distance=3)

Input: V=4, adj = [[[1, 1], [3, 2]],[[0, 1], [2, 4]],[[1, 4], [3, 3]], [[0, 2], [2, 3]]], S=0

Constraints

  • 1 ≤ V ≤ 10000
  • 0 ≤ adj[i][j] ≤ 10000
  • 1 ≤ adj.size() ≤ [ (V*(V - 1)) / 2 ]
  • 0 ≤ S < V

Hints

  • Initialize a distance array dist[] where dist[i] stores the shortest known distance from S to i. Set all distances to 10^9 (infinity) except dist[S] = 0. Use a Min-Heap (Priority Queue) to always expand the current closest node.
  • For each node, check all adjacent nodes and relax their distances (dist[v] = min(dist[v], dist[u] + weight)). Continue until all nodes are processed.

Company Tags

Texas Instruments Activision Blizzard Electronic Arts Bungie Ubisoft Western Digital Philips Healthcare Micron Technology Goldman Sachs Stripe Target Bain & Company Zoho Visa Snowflake Zomato AMD HCL Technologies Dropbox Epic Games IBM Square Splunk Byju's JPMorgan Chase Google Microsoft Amazon Meta Apple Netflix Adobe