


For the given graph,
The shortest distance between 1 and 3 is 2 (via 1 <-> 2 <-> 3). Hence, the answer is 2.
The first line of the input contains an integer, 'T,’ denoting the number of test cases.
The first line of each test case contains two space-separated integers, ‘V’ and ‘E’, denoting the number of vertices and the number of edges in the graph.
The next ‘E’ lines of each test case contain two space-separated integers, ‘vertex1’ and ‘vertex2’, corresponding to ‘vertex1’ and ‘vertex2’ are connected with a bidirectional edge.
The last line of each test case contains two space-separated integers, ‘src’ and ’dest’, representing two vertices whose minimum distance should be calculated.
For each test case, print a single integer representing the shortest distance between the given two vertices, ‘src’ and ‘dest’.
Print the output of each test case in a separate line.
You do not need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 5
1 <= V <= 10^5
V - 1 <= E <= 10^5
1 <= vertex1 , vertex2 <= V
1 <= src, dest <= V
Time limit: 1 sec
In this approach, we will calculate the shortest path between all pairs using the values of already computed values. This algorithm is known as Floyd Warshall Algorithm.
Floyd Warshall Algorithm is a dynamic programming approach in which the shortest distance of a pair is tried to minimize using an intermediate vertex whose value is already calculated as given below:
dist[index1][index2]=min(dis[index1][index2],dis[index1][k] + dis[k][index2])
Where k is the intermediate vertex.
We will run Dijkstra Algorithm for vertex ‘src’ and store the minimum distance of all vertices from vertex ‘src’ in an array in this approach. Then we can return the shortest distance between ‘src’ and ‘dest’.
Dijkstra Algorithm is one of the most popular algorithms in graph theory. A single-source shortest path algorithm gives the shortest path length to all vertices from a given vertex known as the source vertex. It is a greedy algorithm that uses a priority queue(Binary Heap) to pick the shortest distance edges until the minimum distance of all vertices is calculated.
This approach will use breadth-first search traversal to find the shortest path between src and dest. Breadth-First Search is the most common graph traversal technique which satisfies some property. BFS can be related similar to level order traversal in trees.
We will maintain a queue and run BFS starting from vertex src till vertex dest is found and keep track of the traversal order. After visiting any specific node, we will insert all its children in the queue that have never been visited before.