Shortest Path in a weighted Graph where weight of an edge is 1 or 2

Given a directed graph where every edge has weight as either 1 or 2, find the shortest path from a given source vertex āsā to a given destination vertex ātā. Expected time complexity is O(V+E).Ā
A Simple Solution is to use Dijkstraās shortest path algorithm, we can get a shortest path in O(E + VLogV) time.Ā
How to do it in O(V+E) time?Ā
The idea is to use BFS. One important observation about BFS is that the path used in BFS always has the least number of edges between any two vertices. So if all edges are of same weight, we can use BFS to find the shortest path. For this problem, we can modify the graph and split all edges of weight 2 into two edges of weight 1 each. We can use BFS to find the shortest path in the modified graph.Ā
How many new intermediate vertices are needed?Ā
We need to add a new intermediate vertex for every source vertex. The reason is simple, if we add an intermediate vertex x between u and v and if we add same vertex between y and z, then new paths u to z and y to v are added to the graph which might have not been there in the original graph. Therefore in a graph with V vertices, we need V extra vertices. Below is the C++ implementation of the above idea. In the below implementation 2*V vertices are created in a graph and for every edge (u, v), we split it into two edges (u, u+V) and (u+V, w). This way, we ensure that a different intermediate vertex is added for every source vertex.Ā
Implementation:
C++
// Program to shortest path from a given source vertex āsā to // a given destination vertex ātā. Expected time complexity // is O(V+E). #include<bits/stdc++.h> using namespace std; Ā
// This class represents a directed graph using adjacency // list representation class Graph { Ā Ā Ā Ā int V; // No. of vertices Ā Ā Ā Ā list<int> *adj; // adjacency lists public: Ā Ā Ā Ā Graph(int V); // Constructor Ā Ā Ā Ā void addEdge(int v, int w, int weight); // adds an edge Ā
Ā Ā Ā Ā // finds shortest path from source vertex āsā to Ā Ā Ā Ā // destination vertex ādā. Ā Ā Ā Ā int findShortestPath(int s, int d); Ā
Ā Ā Ā Ā // print shortest path from a source vertex āsā to Ā Ā Ā Ā // destination vertex ādā. Ā Ā Ā Ā int printShortestPath(int parent[], int s, int d); }; Ā
Graph::Graph(int V) { Ā Ā Ā Ā this->V = V; Ā Ā Ā Ā adj = new list<int>[2*V]; } Ā
void Graph::addEdge(int v, int w, int weight) { Ā Ā Ā Ā // split all edges of weight 2 into two Ā Ā Ā Ā // edges of weight 1 each. The intermediate Ā Ā Ā Ā // vertex number is maximum vertex number + 1, Ā Ā Ā Ā // that is V. Ā Ā Ā Ā if (weight==2) Ā Ā Ā Ā { Ā Ā Ā Ā Ā Ā Ā Ā adj[v].push_back(v+V); Ā Ā Ā Ā Ā Ā Ā Ā adj[v+V].push_back(w); Ā Ā Ā Ā } Ā Ā Ā Ā else // Weight is 1 Ā Ā Ā Ā Ā Ā Ā Ā adj[v].push_back(w); // Add w to vās list. } Ā
// To print the shortest path stored in parent[] int Graph::printShortestPath(int parent[], int s, int d) { Ā Ā Ā Ā static int level = 0; Ā
Ā Ā Ā Ā // If we reached root of shortest path tree Ā Ā Ā Ā if (parent[s] == -1) Ā Ā Ā Ā { Ā Ā Ā Ā Ā Ā Ā Ā cout << "Shortest Path between " << s << " and "Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā << d << " is " << s << " "; Ā Ā Ā Ā Ā Ā Ā Ā return level; Ā Ā Ā Ā } Ā
Ā Ā Ā Ā printShortestPath(parent, parent[s], d); Ā
Ā Ā Ā Ā level++; Ā Ā Ā Ā if (s < V) Ā Ā Ā Ā Ā Ā Ā Ā cout << s << " "; Ā
Ā Ā Ā Ā return level; } Ā
// This function mainly does BFS and prints the // shortest path from src to dest. It is assumed // that weight of every edge is 1 int Graph::findShortestPath(int src, int dest) { Ā Ā Ā Ā // Mark all the vertices as not visited Ā Ā Ā Ā bool *visited = new bool[2*V]; Ā Ā Ā Ā int *parent = new int[2*V]; Ā
Ā Ā Ā Ā // Initialize parent[] and visited[] Ā Ā Ā Ā for (int i = 0; i < 2*V; i++) Ā Ā Ā Ā { Ā Ā Ā Ā Ā Ā Ā Ā visited[i] = false; Ā Ā Ā Ā Ā Ā Ā Ā parent[i] = -1; Ā Ā Ā Ā } Ā
Ā Ā Ā Ā // Create a queue for BFS Ā Ā Ā Ā list<int> queue; Ā
Ā Ā Ā Ā // Mark the current node as visited and enqueue it Ā Ā Ā Ā visited[src] = true; Ā Ā Ā Ā queue.push_back(src); Ā
Ā Ā Ā Ā // 'i' will be used to get all adjacent vertices of a vertex Ā Ā Ā Ā list<int>::iterator i; Ā
Ā Ā Ā Ā while (!queue.empty()) Ā Ā Ā Ā { Ā Ā Ā Ā Ā Ā Ā Ā // Dequeue a vertex from queue and print it Ā Ā Ā Ā Ā Ā Ā Ā int s = queue.front(); Ā
Ā Ā Ā Ā Ā Ā Ā Ā if (s == dest) Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā return printShortestPath(parent, s, dest); Ā
Ā Ā Ā Ā Ā Ā Ā Ā queue.pop_front(); Ā
Ā Ā Ā Ā Ā Ā Ā Ā // Get all adjacent vertices of the dequeued vertex s Ā Ā Ā Ā Ā Ā Ā Ā // If a adjacent has not been visited, then mark it Ā Ā Ā Ā Ā Ā Ā Ā // visited and enqueue it Ā Ā Ā Ā Ā Ā Ā Ā for (i = adj[s].begin(); i != adj[s].end(); ++i) Ā Ā Ā Ā Ā Ā Ā Ā { Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā if (!visited[*i]) Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā { Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā visited[*i] = true; Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā queue.push_back(*i); Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā parent[*i] = s; Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā } Ā Ā Ā Ā Ā Ā Ā Ā } Ā Ā Ā Ā } } Ā
// Driver program to test methods of graph class int main() { Ā Ā Ā Ā // Create a graph given in the above diagram Ā Ā Ā Ā int V = 4; Ā Ā Ā Ā Graph g(V); Ā Ā Ā Ā g.addEdge(0, 1, 2); Ā Ā Ā Ā g.addEdge(0, 2, 2); Ā Ā Ā Ā g.addEdge(1, 2, 1); Ā Ā Ā Ā g.addEdge(1, 3, 1); Ā Ā Ā Ā g.addEdge(2, 0, 1); Ā Ā Ā Ā g.addEdge(2, 3, 2); Ā Ā Ā Ā g.addEdge(3, 3, 2); Ā
Ā Ā Ā Ā int src = 0, dest = 3; Ā Ā Ā Ā cout << "\nShortest Distance between " << src Ā Ā Ā Ā Ā Ā Ā Ā << " and " << dest << " is "Ā Ā Ā Ā Ā Ā Ā Ā << g.findShortestPath(src, dest); Ā
Ā Ā Ā Ā return 0; } |
Java
// Java to shortest path from a given source vertex 's' to // a given destination vertex 't'. Expected time complexity // is O(V+E). import java.util.*;Ā
class GFG {Ā
Ā Ā Ā Ā // This class represents a directed graph using adjacencyĀ Ā Ā Ā // list representationĀ Ā Ā Ā static class Graph Ā Ā Ā Ā {Ā Ā Ā Ā Ā Ā Ā Ā int V; // No. of verticesĀ Ā Ā Ā Ā Ā Ā Ā Vector<Integer>[] adj; // No. of verticesĀ
Ā Ā Ā Ā Ā Ā Ā Ā static int level;Ā
Ā Ā Ā Ā Ā Ā Ā Ā // ConstructorĀ Ā Ā Ā Ā Ā Ā Ā @SuppressWarnings("unchecked")Ā Ā Ā Ā Ā Ā Ā Ā Graph(int V)Ā Ā Ā Ā Ā Ā Ā Ā {Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā this.V = V;Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā this.adj = new Vector[2 * V];Ā
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā for (int i = 0; i < 2 * V; i++)Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā this.adj[i] = new Vector<>();Ā Ā Ā Ā Ā Ā Ā Ā }Ā
Ā Ā Ā Ā Ā Ā Ā Ā // adds an edgeĀ Ā Ā Ā Ā Ā Ā Ā public void addEdge(int v, int w, int weight)Ā Ā Ā Ā Ā Ā Ā Ā {Ā
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā // split all edges of weight 2 into twoĀ Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā // edges of weight 1 each. The intermediateĀ Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā // vertex number is maximum vertex number + 1,Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā // that is V.Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā if (weight == 2) Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā {Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā adj[v].add(v + this.V);Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā adj[v + this.V].add(w);Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā } else // Weight is 1Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā adj[v].add(w); // Add w to v's list.Ā Ā Ā Ā Ā Ā Ā Ā }Ā
Ā Ā Ā Ā Ā Ā Ā Ā // print shortest path from a source vertex 's' toĀ Ā Ā Ā Ā Ā Ā Ā // destination vertex 'd'.Ā Ā Ā Ā Ā Ā Ā Ā public int printShortestPath(int[] parent, int s, int d)Ā Ā Ā Ā Ā Ā Ā Ā {Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā level = 0;Ā
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā // If we reached root of shortest path treeĀ Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā if (parent[s] == -1)Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā {Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā System.out.printf("Shortest Path between"+ Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā "%d and %d is %s ", s, d, s);Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā return level;Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā }Ā
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā printShortestPath(parent, parent[s], d);Ā
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā level++;Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā if (s < this.V)Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā System.out.printf("%d ", s);Ā
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā return level;Ā Ā Ā Ā Ā Ā Ā Ā }Ā
Ā Ā Ā Ā Ā Ā Ā Ā // finds shortest path from source vertex 's' toĀ Ā Ā Ā Ā Ā Ā Ā // destination vertex 'd'.Ā
Ā Ā Ā Ā Ā Ā Ā Ā // This function mainly does BFS and prints theĀ Ā Ā Ā Ā Ā Ā Ā // shortest path from src to dest. It is assumedĀ Ā Ā Ā Ā Ā Ā Ā // that weight of every edge is 1Ā Ā Ā Ā Ā Ā Ā Ā public int findShortestPath(int src, int dest)Ā Ā Ā Ā Ā Ā Ā Ā {Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā boolean[] visited = new boolean[2 * this.V];Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā int[] parent = new int[2 * this.V];Ā
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā // Initialize parent[] and visited[]Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā for (int i = 0; i < 2 * this.V; i++) Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā {Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā visited[i] = false;Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā parent[i] = -1;Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā }Ā
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā // Create a queue for BFSĀ Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Queue<Integer> queue = new LinkedList<>();Ā
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā // Mark the current node as visited and enqueue itĀ Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā visited[src] = true;Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā queue.add(src);Ā
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā while (!queue.isEmpty()) Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā {Ā
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā // Dequeue a vertex from queue and print itĀ Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā int s = queue.peek();Ā
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā if (s == dest)Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā return printShortestPath(parent, s, dest);Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā queue.poll();Ā
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā // Get all adjacent vertices of the dequeued vertex sĀ Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā // If a adjacent has not been visited, then mark itĀ Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā // visited and enqueue itĀ Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā for (int i : this.adj[s]) Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā {Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā if (!visited[i]) Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā {Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā visited[i] = true;Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā queue.add(i);Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā parent[i] = s;Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā }Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā }Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā }Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā return 0;Ā Ā Ā Ā Ā Ā Ā Ā }Ā Ā Ā Ā }Ā
Ā Ā Ā Ā // Driver CodeĀ Ā Ā Ā public static void main(String[] args)Ā Ā Ā Ā {Ā
Ā Ā Ā Ā Ā Ā Ā Ā // Create a graph given in the above diagramĀ Ā Ā Ā Ā Ā Ā Ā int V = 4;Ā Ā Ā Ā Ā Ā Ā Ā Graph g = new Graph(V);Ā Ā Ā Ā Ā Ā Ā Ā g.addEdge(0, 1, 2);Ā Ā Ā Ā Ā Ā Ā Ā g.addEdge(0, 2, 2);Ā Ā Ā Ā Ā Ā Ā Ā g.addEdge(1, 2, 1);Ā Ā Ā Ā Ā Ā Ā Ā g.addEdge(1, 3, 1);Ā Ā Ā Ā Ā Ā Ā Ā g.addEdge(2, 0, 1);Ā Ā Ā Ā Ā Ā Ā Ā g.addEdge(2, 3, 2);Ā Ā Ā Ā Ā Ā Ā Ā g.addEdge(3, 3, 2);Ā
Ā Ā Ā Ā Ā Ā Ā Ā int src = 0, dest = 3;Ā Ā Ā Ā Ā Ā Ā Ā System.out.printf("\nShortest Distance between" + Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā " %d and %d is %d\n", src, Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā dest, g.findShortestPath(src, dest));Ā Ā Ā Ā }}Ā
// This code is contributed by// sanjeev2552 |
Python
'''Ā Program to shortest path from a given source vertex s toĀ Ā Ā Ā a given destination vertex t.Ā Expected time complexityĀ Ā Ā Ā is O(V+E)'''from collections import defaultdictĀ Ā #This class represents a directed graph using adjacency list representationclass Graph:Ā Ā Ā Ā Ā Ā def __init__(self,vertices):Ā Ā Ā Ā Ā Ā Ā Ā self.V = vertices #No. of verticesĀ Ā Ā Ā Ā Ā Ā Ā self.V_org = verticesĀ Ā Ā Ā Ā Ā Ā Ā self.graph = defaultdict(list) # default dictionary to store graphĀ Ā Ā Ā Ā Ā # function to add an edge to graphĀ Ā Ā Ā def addEdge(self,u,v,w):Ā Ā Ā Ā Ā Ā Ā Ā if w == 1:Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā self.graph[u].append(v)Ā Ā Ā Ā Ā Ā Ā Ā else:Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā '''split all edges of weight 2 into twoĀ Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā edges of weight 1 each.Ā The intermediateĀ Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā vertex number is maximum vertex number + 1,Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā that is V.'''Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā self.graph[u].append(self.V)Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā self.graph[self.V].append(v)Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā self.V = self.V + 1Ā Ā Ā Ā Ā Ā Ā Ā Ā # To print the shortest path stored in parent[]Ā Ā Ā Ā def printPath(self, parent, j):Ā Ā Ā Ā Ā Ā Ā Ā Path_len = 1Ā Ā Ā Ā Ā Ā Ā Ā if parent[j] == -1 and j < self.V_org : #Base Case : If j is sourceĀ Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā print j,Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā return 0 # when parent[-1] then path length = 0Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā l = self.printPath(parent , parent[j])Ā
Ā Ā Ā Ā Ā Ā Ā Ā #increment path lengthĀ Ā Ā Ā Ā Ā Ā Ā Path_len = l + Path_lenĀ
Ā Ā Ā Ā Ā Ā Ā Ā # print node only if its less than original node length.Ā Ā Ā Ā Ā Ā Ā Ā # i.e do not print any new node that has been added laterĀ Ā Ā Ā Ā Ā Ā Ā if j < self.V_org : Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā print j,Ā
Ā Ā Ā Ā Ā Ā Ā Ā return Path_lenĀ
Ā Ā Ā Ā Ā '''Ā Ā Ā This function mainly does BFS and prints theĀ Ā Ā Ā Ā Ā Ā Ā shortest path from src to dest. It is assumedĀ Ā Ā Ā Ā Ā Ā Ā that weight of every edge is 1'''Ā Ā Ā Ā def findShortestPath(self,src, dest):Ā
Ā Ā Ā Ā Ā Ā Ā Ā # Mark all the vertices as not visitedĀ Ā Ā Ā Ā Ā Ā Ā # Initialize parent[] and visited[]Ā Ā Ā Ā Ā Ā Ā Ā visited =[False]*(self.V)Ā Ā Ā Ā Ā Ā Ā Ā parent =[-1]*(self.V)Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā # Create a queue for BFSĀ Ā Ā Ā Ā Ā Ā Ā queue=[]Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā # Mark the source node as visited and enqueue itĀ Ā Ā Ā Ā Ā Ā Ā queue.append(src)Ā Ā Ā Ā Ā Ā Ā Ā visited[src] = TrueĀ Ā Ā Ā Ā Ā Ā Ā Ā Ā while queue :Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā # Dequeue a vertex from queue Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā s = queue.pop(0)Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā # if s = dest then print the path and returnĀ Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā if s == dest:Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā return self.printPath(parent, s)Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā # Get all adjacent vertices of the dequeued vertex sĀ Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā # If a adjacent has not been visited, then mark itĀ Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā # visited and enqueue itĀ Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā for i in self.graph[s]:Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā if visited[i] == False:Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā queue.append(i)Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā visited[i] = TrueĀ Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā parent[i] = sĀ Ā Ā Ā # Create a graph given in the above diagramg = Graph(4)g.addEdge(0, 1, 2)g.addEdge(0, 2, 2)g.addEdge(1, 2, 1)g.addEdge(1, 3, 1)g.addEdge(2, 0, 1)g.addEdge(2, 3, 2)g.addEdge(3, 3, 2)Ā
src = 0; dest = 3print ("Shortest Path between %d and %d isĀ " %(src, dest)),l = g.findShortestPath(src, dest)print ("\nShortest Distance between %d and %d is %d " %(src, dest, l)),Ā
#This code is contributed by Neelam Yadav |
C#
// C# to shortest path from a given source vertex 's' to // a given destination vertex 't'. Expected time complexity // is O(V+E). using System;using System.Collections.Generic;Ā
class GFG {Ā
Ā Ā Ā Ā // This class represents a directed graph using adjacencyĀ Ā Ā Ā // list representationĀ Ā Ā Ā class Graph Ā Ā Ā Ā {Ā Ā Ā Ā Ā Ā Ā Ā public int V; // No. of verticesĀ Ā Ā Ā Ā Ā Ā Ā public List<int>[] adj; // No. of verticesĀ
Ā Ā Ā Ā Ā Ā Ā Ā static int level;Ā
Ā Ā Ā Ā Ā Ā Ā Ā // ConstructorĀ Ā Ā Ā Ā Ā Ā Ā public Graph(int V)Ā Ā Ā Ā Ā Ā Ā Ā {Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā this.V = V;Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā this.adj = new List<int>[2 * V];Ā
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā for (int i = 0; i < 2 * V; i++)Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā this.adj[i] = new List<int>();Ā Ā Ā Ā Ā Ā Ā Ā }Ā
Ā Ā Ā Ā Ā Ā Ā Ā // adds an edgeĀ Ā Ā Ā Ā Ā Ā Ā public void addEdge(int v, int w, int weight)Ā Ā Ā Ā Ā Ā Ā Ā {Ā
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā // split all edges of weight 2 into twoĀ Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā // edges of weight 1 each. The intermediateĀ Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā // vertex number is maximum vertex number + 1,Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā // that is V.Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā if (weight == 2) Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā {Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā adj[v].Add(v + this.V);Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā adj[v + this.V].Add(w);Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā } else // Weight is 1Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā adj[v].Add(w); // Add w to v's list.Ā Ā Ā Ā Ā Ā Ā Ā }Ā
Ā Ā Ā Ā Ā Ā Ā Ā // print shortest path from a source vertex 's' toĀ Ā Ā Ā Ā Ā Ā Ā // destination vertex 'd'.Ā Ā Ā Ā Ā Ā Ā Ā public int printShortestPath(int[] parent, int s, int d)Ā Ā Ā Ā Ā Ā Ā Ā {Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā level = 0;Ā
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā // If we reached root of shortest path treeĀ Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā if (parent[s] == -1)Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā {Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Console.Write("Shortest Path between"+ Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā "{0} and {1} is {2} ", s, d, s);Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā return level;Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā }Ā
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā printShortestPath(parent, parent[s], d);Ā
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā level++;Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā if (s < this.V)Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Console.Write("{0} ", s);Ā
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā return level;Ā Ā Ā Ā Ā Ā Ā Ā }Ā
Ā Ā Ā Ā Ā Ā Ā Ā // finds shortest path from source vertex 's' toĀ Ā Ā Ā Ā Ā Ā Ā // destination vertex 'd'.Ā
Ā Ā Ā Ā Ā Ā Ā Ā // This function mainly does BFS and prints theĀ Ā Ā Ā Ā Ā Ā Ā // shortest path from src to dest. It is assumedĀ Ā Ā Ā Ā Ā Ā Ā // that weight of every edge is 1Ā Ā Ā Ā Ā Ā Ā Ā public int findShortestPath(int src, int dest)Ā Ā Ā Ā Ā Ā Ā Ā {Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā bool[] visited = new bool[2 * this.V];Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā int[] parent = new int[2 * this.V];Ā
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā // Initialize parent[] and visited[]Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā for (int i = 0; i < 2 * this.V; i++) Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā {Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā visited[i] = false;Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā parent[i] = -1;Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā }Ā
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā // Create a queue for BFSĀ Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā List<int> queue = new List<int>();Ā
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā // Mark the current node as visited and enqueue itĀ Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā visited[src] = true;Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā queue.Add(src);Ā
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā while (queue.Count != 0) Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā {Ā
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā // Dequeue a vertex from queue and print itĀ Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā int s = queue[0];Ā
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā if (s == dest)Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā return printShortestPath(parent, s, dest);Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā queue.RemoveAt(0);Ā
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā // Get all adjacent vertices of the dequeued vertex sĀ Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā // If a adjacent has not been visited, then mark itĀ Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā // visited and enqueue itĀ Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā foreach (int i in this.adj[s]) Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā {Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā if (!visited[i]) Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā {Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā visited[i] = true;Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā queue.Add(i);Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā parent[i] = s;Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā }Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā }Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā }Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā return 0;Ā Ā Ā Ā Ā Ā Ā Ā }Ā Ā Ā Ā }Ā
Ā Ā Ā Ā // Driver CodeĀ Ā Ā Ā public static void Main(String[] args)Ā Ā Ā Ā {Ā
Ā Ā Ā Ā Ā Ā Ā Ā // Create a graph given in the above diagramĀ Ā Ā Ā Ā Ā Ā Ā int V = 4;Ā Ā Ā Ā Ā Ā Ā Ā Graph g = new Graph(V);Ā Ā Ā Ā Ā Ā Ā Ā g.addEdge(0, 1, 2);Ā Ā Ā Ā Ā Ā Ā Ā g.addEdge(0, 2, 2);Ā Ā Ā Ā Ā Ā Ā Ā g.addEdge(1, 2, 1);Ā Ā Ā Ā Ā Ā Ā Ā g.addEdge(1, 3, 1);Ā Ā Ā Ā Ā Ā Ā Ā g.addEdge(2, 0, 1);Ā Ā Ā Ā Ā Ā Ā Ā g.addEdge(2, 3, 2);Ā Ā Ā Ā Ā Ā Ā Ā g.addEdge(3, 3, 2);Ā
Ā Ā Ā Ā Ā Ā Ā Ā int src = 0, dest = 3;Ā Ā Ā Ā Ā Ā Ā Ā Console.Write("\nShortest Distance between" + Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā " {0} and {1} is {2}\n", src, Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā dest, g.findShortestPath(src, dest));Ā Ā Ā Ā }}Ā
// This code is contributed by PrinciRaj1992 |
Javascript
<script>// Javascript program to find shortest path // from a given source vertex 's' to// a given destination vertex 't'. Expected time complexity// is O(V+E).Ā
Ā
// This class represents a directed graph using adjacency// list representationclass Graph{Ā Ā Ā Ā constructor(V)Ā Ā Ā Ā {Ā Ā Ā Ā Ā Ā Ā Ā this.V = V;Ā Ā Ā Ā Ā Ā Ā Ā this.adj = new Array(2 * V);Ā Ā Ā Ā Ā Ā Ā Ā this.level = 0;Ā Ā Ā Ā Ā Ā Ā Ā for (let i = 0; i < 2 * V; i++)Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā this.adj[i] = [];Ā Ā Ā Ā }Ā
Ā Ā Ā Ā // adds an edgeĀ Ā Ā Ā addEdge(v, w, weight)Ā Ā Ā Ā {Ā Ā Ā Ā Ā Ā Ā Ā // split all edges of weight 2 into twoĀ Ā Ā Ā Ā Ā Ā Ā // edges of weight 1 each. The intermediateĀ Ā Ā Ā Ā Ā Ā Ā // vertex number is maximum vertex number + 1,Ā Ā Ā Ā Ā Ā Ā Ā // that is V.Ā Ā Ā Ā Ā Ā Ā Ā if (weight == 2)Ā Ā Ā Ā Ā Ā Ā Ā {Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā this.adj[v].push(v + this.V);Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā this.adj[v + this.V].push(w);Ā Ā Ā Ā Ā Ā Ā Ā } else // Weight is 1Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā this.adj[v].push(w); // Add w to v's list.Ā Ā Ā Ā }Ā
Ā Ā Ā Ā // print shortest path from a source vertex 's' toĀ Ā Ā Ā // destination vertex 'd'.Ā Ā Ā Ā printShortestPath(parent, s, d)Ā Ā Ā Ā {Ā Ā Ā Ā Ā Ā Ā Ā this.level = 0;Ā
Ā Ā Ā Ā Ā Ā Ā Ā // If we reached root of shortest path treeĀ Ā Ā Ā Ā Ā Ā Ā if (parent[s] == -1)Ā Ā Ā Ā Ā Ā Ā Ā {Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā document.write("Shortest Path between " + s + " and " + d + " is " + s + " "); Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā return this.level;Ā Ā Ā Ā Ā Ā Ā Ā }Ā
Ā Ā Ā Ā Ā Ā Ā Ā this.printShortestPath(parent, parent[s], d);Ā
Ā Ā Ā Ā Ā Ā Ā Ā this.level++;Ā Ā Ā Ā Ā Ā Ā Ā if (s < this.V)Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā document.write(s + " ");Ā
Ā Ā Ā Ā Ā Ā Ā Ā return this.level;Ā Ā Ā Ā }Ā
Ā Ā Ā Ā // finds shortest path from source vertex 's' toĀ Ā Ā Ā // destination vertex 'd'.Ā
Ā Ā Ā Ā // This function mainly does BFS and prints theĀ Ā Ā Ā // shortest path from src to dest. It is assumedĀ Ā Ā Ā // that weight of every edge is 1Ā Ā Ā Ā findShortestPath(src, dest)Ā Ā Ā Ā {Ā Ā Ā Ā Ā Ā Ā Ā let visited = new Array(2 * this.V);Ā Ā Ā Ā Ā Ā Ā Ā let parent = new Array(2 * this.V);Ā
Ā Ā Ā Ā Ā Ā Ā Ā // Initialize parent[] and visited[]Ā Ā Ā Ā Ā Ā Ā Ā for (let i = 0; i < 2 * this.V; i++)Ā Ā Ā Ā Ā Ā Ā Ā {Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā visited[i] = false;Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā parent[i] = -1;Ā Ā Ā Ā Ā Ā Ā Ā }Ā
Ā Ā Ā Ā Ā Ā Ā Ā // Create a queue for BFSĀ Ā Ā Ā Ā Ā Ā Ā let queue = [];Ā
Ā Ā Ā Ā Ā Ā Ā Ā // Mark the current node as visited and enqueue itĀ Ā Ā Ā Ā Ā Ā Ā visited[src] = true;Ā Ā Ā Ā Ā Ā Ā Ā queue.push(src);Ā
Ā Ā Ā Ā Ā Ā Ā Ā while (queue.length > 0)Ā Ā Ā Ā Ā Ā Ā Ā {Ā
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā // Dequeue a vertex from queue and print itĀ Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā let s = queue[0];Ā
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā if (s == dest)Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā return this.printShortestPath(parent, s, dest);Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā queue.shift();Ā
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā // Get all adjacent vertices of the dequeued vertex sĀ Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā // If a adjacent has not been visited, then mark itĀ Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā // visited and enqueue itĀ Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā this.adj[s].forEach(i => {Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā if (!visited[i]){Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā visited[i] = true;Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā queue.push(i);Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā parent[i] = s;Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā }Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā });Ā Ā Ā Ā Ā Ā Ā Ā }Ā Ā Ā Ā Ā Ā Ā Ā return 0;Ā Ā Ā Ā }}Ā
// Driver Code// Create a graph given in the above diagramlet V = 4;let g = new Graph(V);g.addEdge(0, 1, 2);g.addEdge(0, 2, 2);g.addEdge(1, 2, 1);g.addEdge(1, 3, 1);g.addEdge(2, 0, 1);g.addEdge(2, 3, 2);g.addEdge(3, 3, 2);Ā
let src = 0, dest = 3;document.write("<br />Shortest Distance between " + src + " and " + dest + " is " + Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā g.findShortestPath(src, dest));Ā
Ā
// This code is contributed by cavi4762Ā
</script> |
Shortest Path between 0 and 3 is 0 1 3 Shortest Distance between 0 and 3 is 3
Time Complexity: O(V + E)
In this algorithm, we do a Breadth First Traversal of the given graph.Ā
The time complexity of BFS is O(V + E) where V is the number of vertices and E is the number of edges in the graph.
Space Complexity: O(V)
The space complexity for this algorithm is O(V), where V is the number of vertices in the graph.Ā
We need to store the visited array of size V and a parent array of size V.
How is this approach O(V+E)? In worst case, all edges are of weight 2 and we need to do O(E) operations to split all edges and 2V vertices, so the time complexity becomes O(E) + O(V+E) which is O(V+E). This article is contributed by Aditya Goel.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



