Given an unweighted directed graph and Q queries consisting of sequences of traversal between two nodes of the graph, the task is to find out if the sequences represent one of the shortest paths between the two nodes.
Input: 1 2 3 4 Output: NO Explanation: The first and last node of the input sequence is 1 and 4 respectively. The shortest path between 1 and 4 is 1 -> 3 -> 4 hence, the output is NO for the 1st example. Input: 1 3 4 Output: YES
The idea is to use Floyd Warshall Algorithm to store the length of all pairs of vertices. If the length of the shortest path between the starting and ending node of the sequence is one less than the length of the sequence, then the given sequence represents one of the shortest paths between the nodes.
Below is the implementation of above approach:
Time complexity: O(V^3)
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.