Given a directed weighted graph and the source and destination vertex. The task is to find the sum of shortest distance on the path going from source to destination and and then from destination to source such that both the paths have at least a common vertex other than the source and the destination.
Note: On going from destination to source, all the directions of the edges are reversed.
Input: src = 0, des = 1
Common vertex is 4 and path is 0 -> 4 -> 3 -> 1 -> 4 -> 0
Approach: The idea is to use Dijkstra’s algorithm. On finding the shortest path from source to destination and shortest path from destination to the source using Dijkstra’s algorithm, it may not result in a path where there is at least one node in common except the source and destination vertex.
- Let s be the source vertex and d be destination vertex and v be the intermediate node common in both the paths from source to destination and destination to source. The shortest pair of paths, so that v is in intersection of this two paths is a path: s -> v -> d -> v -> s and it’s length is
dis[s][v] + dis[v][d] + dis[d][v] + dis[v][s]
- Since s and d are fixed, just find v such that it gives shortest path.
- In order to find such v, follow the below steps:
- Find shortest distance from all vertices to s and d which gives us the values of dis[v][s] and dis[v][d]. For finding the shortest path from all the vertices to a given node refer Shortest paths from all vertices to a destination.
- Find shortest distance of all vertex from s and d which gives us d[s][v] and d[d][v].
- Iterate for all v and find minimum of d[s][v] + d[v][d] + d[d][v] + d[v][s].
Below is the implementation of the above approach:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.