Path Queries
You are given a weighted, undirected graph with ‘V’ vertices numbered from 1 to ‘V’ and ‘E’ bidirectional edges.
You have to answer ‘Q’ queries. Every query has two integers, ‘u’, ‘v’, representing the vertices. Your task is to print the shortest distance between ‘u’ and ‘v’ and print -1 if there is no path.
For example:
For the given graph, we have to find the shortest distance between vertices 1 and 3.
The shortest distance between 1 and 3 is 2 (via 1 <-> 2<-> 3). Hence, the answer is 2.
Input Format:
The first line of the input contains an integer, 'T,’ denoting the number of test cases.
The first line of each test case contains three integers ‘V’, ‘E’, ‘Q’, denoting the number of vertices, the number of edges in the graph, and the number of queries.
The Next ‘E’ lines of each test case have three integers ‘u’,’v’,’w’ corresponding to vertices ‘u’ and ‘v’ are connected with a weight ‘w’.
The Next ‘Q’ lines of each test case have two integers, ‘u’,’v’ representing two vertices.
Output Format:
For each test case, print ‘Q’ lines, each line has one integer corresponding to the minimum distance for the given query.
Print the output of each test case in a separate line.
Note:
You do not need to print anything. It has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 5
1 <= V <= 100
1 <= E <= (V *(V - 1)) / 2
1 <= Q <= 10^5
1 <= u , v <= V
1 <= w <= 10^6
Time limit: 1 sec
CodingNinjas
author
2y
Dijkstra Algorithm
We will run Dijkstra Algorithm for all vertices in this approach and store the minimum distance in an array. Then we can answer the queries using this distance array.
Dijkstra Algori...read more
CodingNinjas
author
2y
Floyd Warshall Algorithm
In this approach, we will calculate the shortest path between all pairs of vertices using already computed values. This algorithm is known as Floyd Warshall Algorithm.
Floyd War...read more
Help your peers!
Add answer anonymously...
Top Lido Learning Software Developer interview questions & answers
Popular interview questions of Software Developer
>
Lido Learning Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+
Reviews
4 L+
Interviews
4 Cr+
Salaries
1 Cr+
Users/Month
Contribute to help millions
Get AmbitionBox app