Given an unweighted graph, a source, and a destination, we need to find the shortest path from source to destination in the graph in the most optimal way.

unweighted graph of 8 vertices
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
One solution is to solve in O(VE) time using Bellman–Ford. If there are no negative weight cycles, then we can solve in O(E + VLogV) time using Dijkstra’s algorithm.
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.
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 the algorithm is spent in doing the Breadth-first search from a given source which we know takes O(V+E) time. Thus the 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:
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
void add_edge(vector<int> adj[], int src, int dest)
{
adj[src].push_back(dest);
adj[dest].push_back(src);
}
bool BFS(vector<int> adj[], int src, int dest, int v,
int pred[], int dist[])
{
list<int> queue;
bool visited[v];
for (int i = 0; i < v; i++) {
visited[i] = false;
dist[i] = INT_MAX;
pred[i] = -1;
}
visited[src] = true;
dist[src] = 0;
queue.push_back(src);
while (!queue.empty()) {
int u = queue.front();
queue.pop_front();
for (int i = 0; i < adj[u].size(); i++) {
if (visited[adj[u][i]] == false) {
visited[adj[u][i]] = true;
dist[adj[u][i]] = dist[u] + 1;
pred[adj[u][i]] = u;
queue.push_back(adj[u][i]);
if (adj[u][i] == dest)
return true;
}
}
}
return false;
}
void printShortestDistance(vector<int> adj[], int s,
int dest, int v)
{
int pred[v], dist[v];
if (BFS(adj, s, dest, v, pred, dist) == false) {
cout << "Given source and destination"
<< " are not connected";
return;
}
vector<int> path;
int crawl = dest;
path.push_back(crawl);
while (pred[crawl] != -1) {
path.push_back(pred[crawl]);
crawl = pred[crawl];
}
cout << "Shortest path length is : "
<< dist[dest];
cout << "\nPath is::\n";
for (int i = path.size() - 1; i >= 0; i--)
cout << path[i] << " ";
}
int main()
{
int v = 8;
vector<int> adj[v];
add_edge(adj, 0, 1);
add_edge(adj, 0, 3);
add_edge(adj, 1, 2);
add_edge(adj, 3, 4);
add_edge(adj, 3, 7);
add_edge(adj, 4, 5);
add_edge(adj, 4, 6);
add_edge(adj, 4, 7);
add_edge(adj, 5, 6);
add_edge(adj, 6, 7);
int source = 0, dest = 7;
printShortestDistance(adj, source, dest, v);
return 0;
}
|
Java
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
public class pathUnweighted {
public static void main(String args[])
{
int v = 8;
ArrayList<ArrayList<Integer>> adj =
new ArrayList<ArrayList<Integer>>(v);
for (int i = 0; i < v; i++) {
adj.add(new ArrayList<Integer>());
}
addEdge(adj, 0, 1);
addEdge(adj, 0, 3);
addEdge(adj, 1, 2);
addEdge(adj, 3, 4);
addEdge(adj, 3, 7);
addEdge(adj, 4, 5);
addEdge(adj, 4, 6);
addEdge(adj, 4, 7);
addEdge(adj, 5, 6);
addEdge(adj, 6, 7);
int source = 0, dest = 7;
printShortestDistance(adj, source, dest, v);
}
private static void addEdge(ArrayList<ArrayList<Integer>> adj, int i, int j)
{
adj.get(i).add(j);
adj.get(j).add(i);
}
private static void printShortestDistance(
ArrayList<ArrayList<Integer>> adj,
int s, int dest, int v)
{
int pred[] = new int[v];
int dist[] = new int[v];
if (BFS(adj, s, dest, v, pred, dist) == false) {
System.out.println("Given source and destination" +
"are not connected");
return;
}
LinkedList<Integer> path = new LinkedList<Integer>();
int crawl = dest;
path.add(crawl);
while (pred[crawl] != -1) {
path.add(pred[crawl]);
crawl = pred[crawl];
}
System.out.println("Shortest path length is: " + dist[dest]);
System.out.println("Path is ::");
for (int i = path.size() - 1; i >= 0; i--) {
System.out.print(path.get(i) + " ");
}
}
private static boolean BFS(ArrayList<ArrayList<Integer>> adj, int src,
int dest, int v, int pred[], int dist[])
{
LinkedList<Integer> queue = new LinkedList<Integer>();
boolean visited[] = new boolean[v];
for (int i = 0; i < v; i++) {
visited[i] = false;
dist[i] = Integer.MAX_VALUE;
pred[i] = -1;
}
visited[src] = true;
dist[src] = 0;
queue.add(src);
while (!queue.isEmpty()) {
int u = queue.remove();
for (int i = 0; i < adj.get(u).size(); i++) {
if (visited[adj.get(u).get(i)] == false) {
visited[adj.get(u).get(i)] = true;
dist[adj.get(u).get(i)] = dist[u] + 1;
pred[adj.get(u).get(i)] = u;
queue.add(adj.get(u).get(i));
if (adj.get(u).get(i) == dest)
return true;
}
}
}
return false;
}
}
|
Python3
def add_edge(adj, src, dest):
adj[src].append(dest);
adj[dest].append(src);
def BFS(adj, src, dest, v, pred, dist):
queue = []
visited = [False for i in range(v)];
for i in range(v):
dist[i] = 1000000
pred[i] = -1;
visited[src] = True;
dist[src] = 0;
queue.append(src);
while (len(queue) != 0):
u = queue[0];
queue.pop(0);
for i in range(len(adj[u])):
if (visited[adj[u][i]] == False):
visited[adj[u][i]] = True;
dist[adj[u][i]] = dist[u] + 1;
pred[adj[u][i]] = u;
queue.append(adj[u][i]);
if (adj[u][i] == dest):
return True;
return False;
def printShortestDistance(adj, s, dest, v):
pred=[0 for i in range(v)]
dist=[0 for i in range(v)];
if (BFS(adj, s, dest, v, pred, dist) == False):
print("Given source and destination are not connected")
path = []
crawl = dest;
path.append(crawl);
while (pred[crawl] != -1):
path.append(pred[crawl]);
crawl = pred[crawl];
print("Shortest path length is : " + str(dist[dest]), end = '')
print("\nPath is : : ")
for i in range(len(path)-1, -1, -1):
print(path[i], end=' ')
if __name__=='__main__':
v = 8;
adj = [[] for i in range(v)];
add_edge(adj, 0, 1);
add_edge(adj, 0, 3);
add_edge(adj, 1, 2);
add_edge(adj, 3, 4);
add_edge(adj, 3, 7);
add_edge(adj, 4, 5);
add_edge(adj, 4, 6);
add_edge(adj, 4, 7);
add_edge(adj, 5, 6);
add_edge(adj, 6, 7);
source = 0
dest = 7;
printShortestDistance(adj, source, dest, v);
|
C#
using System;
using System.Collections.Generic;
class pathUnweighted{
public static void Main(String []args)
{
int v = 8;
List<List<int>> adj =
new List<List<int>>(v);
for (int i = 0; i < v; i++)
{
adj.Add(new List<int>());
}
addEdge(adj, 0, 1);
addEdge(adj, 0, 3);
addEdge(adj, 1, 2);
addEdge(adj, 3, 4);
addEdge(adj, 3, 7);
addEdge(adj, 4, 5);
addEdge(adj, 4, 6);
addEdge(adj, 4, 7);
addEdge(adj, 5, 6);
addEdge(adj, 6, 7);
int source = 0, dest = 7;
printShortestDistance(adj, source,
dest, v);
}
private static void addEdge(List<List<int>> adj,
int i, int j)
{
adj[i].Add(j);
adj[j].Add(i);
}
private static void printShortestDistance(List<List<int>> adj,
int s, int dest, int v)
{
int []pred = new int[v];
int []dist = new int[v];
if (BFS(adj, s, dest,
v, pred, dist) == false)
{
Console.WriteLine("Given source and destination" +
"are not connected");
return;
}
List<int> path = new List<int>();
int crawl = dest;
path.Add(crawl);
while (pred[crawl] != -1)
{
path.Add(pred[crawl]);
crawl = pred[crawl];
}
Console.WriteLine("Shortest path length is: " +
dist[dest]);
Console.WriteLine("Path is ::");
for (int i = path.Count - 1;
i >= 0; i--)
{
Console.Write(path[i] + " ");
}
}
private static bool BFS(List<List<int>> adj,
int src, int dest,
int v, int []pred,
int []dist)
{
List<int> queue = new List<int>();
bool []visited = new bool[v];
for (int i = 0; i < v; i++)
{
visited[i] = false;
dist[i] = int.MaxValue;
pred[i] = -1;
}
visited[src] = true;
dist[src] = 0;
queue.Add(src);
while (queue.Count != 0)
{
int u = queue[0];
queue.RemoveAt(0);
for (int i = 0;
i < adj[u].Count; i++)
{
if (visited[adj[u][i]] == false)
{
visited[adj[u][i]] = true;
dist[adj[u][i]] = dist[u] + 1;
pred[adj[u][i]] = u;
queue.Add(adj[u][i]);
if (adj[u][i] == dest)
return true;
}
}
}
return false;
}
}
|
Javascript
const max_value = 9007199254740992;
function add_edge(adj, src, dest){
adj[src].push(dest);
adj[dest].push(src);
}
function BFS(adj, src, dest, v, pred, dist)
{
let queue = [];
let visited = new Array(v);
for (let i = 0; i < v; i++) {
visited[i] = false;
dist[i] = max_value;
pred[i] = -1;
}
visited[src] = true;
dist[src] = 0;
queue.push(src);
while (queue.length > 0) {
let u = queue[0];
queue.shift();
for (let i = 0; i < adj[u].length; i++) {
if (visited[adj[u][i]] == false) {
visited[adj[u][i]] = true;
dist[adj[u][i]] = dist[u] + 1;
pred[adj[u][i]] = u;
queue.push(adj[u][i]);
if (adj[u][i] == dest)
return true;
}
}
}
return false;
}
function printShortestDistance(adj, s, dest, v)
{
let pred = new Array(v).fill(0);
let dist = new Array(v).fill(0);
if (BFS(adj, s, dest, v, pred, dist) == false) {
console.log("Given source and destination are not connected");
}
let path = new Array();
let crawl = dest;
path.push(crawl);
while (pred[crawl] != -1) {
path.push(pred[crawl]);
crawl = pred[crawl];
}
console.log("Shortest path length is : ", dist[dest]);
console.log("Path is::");
for (let i = path.length - 1; i >= 0; i--)
console.log(path[i]);
}
let v = 8;
let adj = new Array(v).fill(0);
for(let i = 0; i < v; i++){
adj[i] = new Array();
}
add_edge(adj, 0, 1);
add_edge(adj, 0, 3);
add_edge(adj, 1, 2);
add_edge(adj, 3, 4);
add_edge(adj, 3, 7);
add_edge(adj, 4, 5);
add_edge(adj, 4, 6);
add_edge(adj, 4, 7);
add_edge(adj, 5, 6);
add_edge(adj, 6, 7);
let source = 0;
let dest = 7;
printShortestDistance(adj, source, dest, v);
|
OutputShortest path length is : 2
Path is::
0 3 7
Time Complexity : O(V + E)
Auxiliary Space: O(V)
Algorithm
Create a queue and add the starting vertex to it.
Create an array to keep track of the distances from the starting vertex to all other vertices. Initialize all distances to infinity except for the starting vertex, which should have a distance of 0.
While the queue is not empty, dequeue the next vertex.
For each neighbor of the dequeued vertex that has not been visited, set its distance to the distance of the dequeued vertex plus 1 and add it to the queue.
Repeat steps 3-4 until the queue is empty.
The distances array now contains the shortest path distances from the starting vertex to all other vertices.
Program
C++
#include <bits/stdc++.h>
using namespace std;
vector<int> bfs_shortest_path(vector<vector<int> >& graph,
int start)
{
deque<int> queue;
queue.push_back(start);
vector<int> distances(graph.size(),
numeric_limits<int>::max());
distances[start]
= 0;
set<int> visited;
while (!queue.empty()) {
int vertex
= queue.front();
queue.pop_front();
visited.insert(
vertex);
for (int neighbor : graph[vertex]) {
if (visited.find(neighbor)
== visited.end()) {
distances[neighbor]
= distances[vertex]
+ 1;
queue.push_back(
neighbor);
}
}
}
return distances;
}
int main()
{
vector<vector<int> > graph = {
{ 1, 2 }, { 2, 3 }, { 3 }, { 4 }, {}
};
int start_vertex = 0;
vector<int> distances = bfs_shortest_path(
graph, start_vertex);
for (int distance : distances) {
cout << distance << " ";
}
cout << endl;
return 0;
}
|
Java
import java.util.*;
public class ShortestPathBFS {
static List<Integer>
bfsShortestPath(List<List<Integer> > graph, int start)
{
Deque<Integer> queue
= new LinkedList<>();
queue.addLast(start);
List<Integer> distances
= new ArrayList<>(Collections.nCopies(
graph.size(), Integer.MAX_VALUE));
distances.set(
start, 0);
Set<Integer> visited
= new HashSet<>();
while (!queue.isEmpty()) {
int vertex = queue.removeFirst();
visited.add(
vertex);
for (int neighbor : graph.get(vertex)) {
if (!visited.contains(
neighbor)) {
distances.set(
neighbor,
distances.get(vertex)
+ 1);
queue.addLast(
neighbor);
}
}
}
return distances;
}
public static void main(String[] args)
{
List<List<Integer> > graph = Arrays.asList(
Arrays.asList(1, 2), Arrays.asList(2, 3),
Arrays.asList(3), Arrays.asList(4),
Collections
.emptyList());
int startVertex = 0;
List<Integer> distances = bfsShortestPath(
graph, startVertex);
for (int distance : distances) {
System.out.print(distance + " ");
}
System.out.println();
}
}
|
Python3
from collections import deque
def bfs_shortest_path(graph, start):
queue = deque([start])
distances = [float('inf')] * len(graph)
distances[start] = 0
visited = set()
while queue:
vertex = queue.popleft()
visited.add(vertex)
for neighbor in graph[vertex]:
if neighbor not in visited:
distances[neighbor] = distances[vertex] + 1
queue.append(neighbor)
return distances
graph = [[1, 2], [2, 3], [3], [4], []]
start_vertex = 0
distances = bfs_shortest_path(graph, start_vertex)
print(distances)
|
C#
using System;
using System.Collections.Generic;
public class GFG
{
public static int[] BfsShortestPath(List<List<int>> graph, int start)
{
Queue<int> queue = new Queue<int>();
queue.Enqueue(start);
int[] distances = new int[graph.Count];
for (int i = 0; i < distances.Length; i++)
{
distances[i] = int.MaxValue;
}
distances[start] = 0;
HashSet<int> visited = new HashSet<int>();
while (queue.Count > 0)
{
int vertex = queue.Dequeue();
visited.Add(vertex);
foreach (int neighbor in graph[vertex])
{
if (!visited.Contains(neighbor))
{
distances[neighbor] = distances[vertex] + 1;
queue.Enqueue(neighbor);
}
}
}
return distances;
}
public static void Main()
{
List<List<int>> graph = new List<List<int>>()
{
new List<int> {1, 2},
new List<int> {2, 3},
new List<int> {3},
new List<int> {4},
new List<int>()
};
int startVertex = 0;
int[] distances = BfsShortestPath(graph, startVertex);
foreach (int distance in distances)
{
Console.Write(distance + " ");
}
Console.WriteLine();
}
}
|
In the above example, the output [0, 1, 1, 2, 3] indicates that the shortest path from vertex 0 to vertex 1 is of length 1, the shortest path from vertex 0 to vertex 2 is also of length 1, and so on.
Time and Auxiliary space
The time complexity of the above BFS-based algorithm for finding the shortest path in an unweighted graph is O(V + E), where V is the number of vertices and E is the number of edges in the graph. This is because each vertex and edge is visited at most once during the BFS traversal.
The space complexity of the algorithm is also O(V + E), due to the use of the distances array to store the shortest distances from the starting vertex to all other vertices, and the visited set to keep track of visited vertices. The queue used for BFS traversal can also have a maximum size of O(V + E) in the worst case, which contributes to the space complexity.
Last Updated :
07 Dec, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...