Given a unweighted graph, a source and a destination, we need to find shortest path from source to destination in the graph in most optimal way.
Input: source vertex = 0 and destination vertex is = 7. Output: Shortest path length is:2 Path is:: 0 3 7 Input: source vertex is = 2 and destination vertex is = 6. Output: Shortest path length is:5 Path is:: 2 1 0 3 4 6
Since the graph is unweighted, we can solve this problem in O(V + E) time. The idea is to use a modified version of Breadth-first search in which we keep storing the predecessor of a given vertex while doing the breadth first search. This algorithm will work even when negative weight cycles are present in the graph.
We first initialize an array dist[0, 1, …., v-1] such that dist[i] stores the distance of vertex i from the source vertex and array pred[0, 1, ….., v-1] such that pred[i] represents the immediate predecessor of the vertex i in the breadth first search starting from the source.
Now we get the length of the path from source to any other vertex in O(1) time from array d, and for printing the path from source to any vertex we can use array p and that will take O(V) time in worst case as V is the size of array P. So most of the time of algorithm is spent in doing the Breadth first search from given source which we know takes O(V+E) time. Thus time complexity of our algorithm is O(V+E).
Take the following unweighted graph as an example:
Following is the complete algorithm for finding the shortest path:
Shortest path length is : 2 Path is:: 0 3 7
Time Complexity : O(V + E)
Auxiliary Space : O(V)
- Multi Source Shortest Path in Unweighted Graph
- Shortest cycle in an undirected unweighted graph
- Number of shortest paths in an unweighted and directed graph
- Multistage Graph (Shortest Path)
- 0-1 BFS (Shortest Path in a Binary Weight Graph)
- Shortest Path in Directed Acyclic Graph
- Shortest Path in a weighted Graph where weight of an edge is 1 or 2
- Shortest path with exactly k edges in a directed and weighted graph
- Graph implementation using STL for competitive programming | Set 1 (DFS of Unweighted and Undirected)
- Shortest path from source to destination such that edge weights along path are alternatively increasing and decreasing
- Convert the undirected graph into directed graph such that there is no path of length greater than 1
- Shortest path in a Binary Maze
- Dijkstra’s shortest path algorithm using set in STL
- Shortest Path using Meet In The Middle
- Some interesting shortest path questions | Set 1
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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.