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.
- Print all shortest paths between given source and destination in an undirected graph
- Check if the given graph represents a Bus Topology
- Check if the given graph represents a Star Topology
- Check if the given graph represents a Ring Topology
- Finding shortest path between any two nodes using Floyd Warshall Algorithm
- Printing Paths in Dijkstra's Shortest Path Algorithm
- Number of shortest paths in an unweighted and directed graph
- Minimum Cost of Simple Path between two nodes in a Directed and Weighted Graph
- Shortest path from source to destination such that edge weights along path are alternatively increasing and decreasing
- Shortest Path in Directed Acyclic Graph
- Shortest path with exactly k edges in a directed and weighted graph
- Shortest Path in a weighted Graph where weight of an edge is 1 or 2
- 0-1 BFS (Shortest Path in a Binary Weight Graph)
- Multistage Graph (Shortest Path)
- Multi Source Shortest Path in Unweighted Graph
- Shortest path with exactly k edges in a directed and weighted graph | Set 2
- Shortest path in a directed graph by Dijkstra’s algorithm
- Building an undirected graph and finding shortest path using Dictionaries in Python
- Shortest path in a complement graph
- Create a Graph by connecting divisors from N to M and find shortest path
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.