Shortest path in undirected graph with unit weights

Graphs Hard Problems Hard
  • This type of algorithm, known as the Shortest Path algorithm, is the foundation of routing on the internet
  • Electric signals travel faster through some types of wires or connections than others, so finding the route that gets data to its destination the quickest is a common application of Shortest Path algorithms
  • They are also used in map applications for finding the quickest route to your destination, accounting not only for distance but also for things like traffic and speed limits

Given a Undirected Graph of N vertices from 0 to N-1 and M edges and a 2D Integer array wdges, where there is a edge from vertex edge[i][0] to vertex edge[i][1] of unit weight.


Find the shortest path from the source to all other nodes in this graph. In this problem statement, we have assumed the source vertex to be ‘0’. If a vertex is unreachable from the source node, then return -1 for that vertex.

Examples:

Input: n = 9, m = 10, edges = [[0,1],[0,3],[3,4],[4,5],[5, 6],[1,2],[2,6],[6,7],[7,8],[6,8]]


Output: 0 1 2 1 2 3 3 4 4


Explanation:

The above output array shows the shortest path to all 

the nodes from the source vertex (0), Dist[0] = 0, Dist[1] = 1 , Dist[2] = 2 , …. Dist[8] = 4.Where Dist[node] is the shortest path between src and the node. For a node, if the value of Dist[node]= -1, then we conclude that the node is unreachable from the src node.

Input: n = 8, m = 10, edges =[[1,0],[2,1],[0,3],[3,7],[3,4],[7,4],[7,6],[4,5],[4,6],[6,5]]


Output: 0 1 2 1 2 3 3 2


Explanation: 

The above output list shows the shortest path to all the nodes from the source vertex (0), Dist[0] = 0, Dist[1] = 1, Dist[2] = 2,.....Dist[7] = 2.

Input: n = 3, m = 1, edges = [[1,2]]

Constraints

  • 1<=n,m<=104
  • 0<=edges[i][j]<=n-1

Hints

  • Perform a topological sort to find an ordering of nodes where every node appears before its dependent nodes. Initialize a distance array with inf (or a large value) for all nodes, except for the source node (0), which is initialized to 0.
  • Process the nodes in topological order, updating the shortest distances for all adjacent nodes using edge relaxation:dist[v]=min(dist[v],dist[u]+weight[u→v]). If a node remains unreachable (inf distance), return -1 for that node

Company Tags

Boston Consulting Group Seagate Technology Activision Blizzard Red Hat Western Digital Epic Systems Splunk NVIDIA Airbnb OYO Rooms HCL Technologies JPMorgan Chase AMD ARM Intel Chewy Nutanix Rockstar Games Robinhood Salesforce Swiggy Optum Micron Technology PwC Twilio Google Microsoft Amazon Meta Apple Netflix Adobe