Given an undirected graph with N vertices (numbered from 0 to N-1), where each edge has a weight of either 0 or 1, and a source vertex. Find the shortest paths from the source vertex to all other vertices in the graph.
[Naive Approach] Using Dijkstra Algorithm - O(E x log (V)) Time and O(V) Space
One Approach would be to use Dijkstra's Algorithm to find the shortest distance from a given source node to all other nodes in the graph. The source node's distance from itself is initialized to zero. From there, we iteratively pick the unprocessed node with the minimum distance from the source, this is where a min-heap or a set is typically used for efficiency.
[Expected Approach] Using Deque - O(V + E) time and O(V + E) space
To solve this problem efficiently, we can use 0-1 BFS, which employs a deque to maintain sorted distances in O(V + E) time. By pushing 0-weight edges to the front for immediate processing and 1-weight edges to the back, we can replicate Dijkstra’s priority logic without the computational overhead of a heap.
C++
#include<iostream>#include<vector>#include<queue>usingnamespacestd;vector<int>minDist(intn,intsrc,vector<vector<vector<int>>>&adj){// Initialize distances to infinityvector<int>dist(n,INT_MAX);dist[src]=0;// Use deque for 0-1 BFSdeque<int>dq;dq.push_back(src);while(!dq.empty()){intu=dq.front();dq.pop_front();// Process all adjacent verticesfor(auto&edge:adj[u]){intv=edge[0];intweight=edge[1];// If we can improve the distanceif(dist[u]+weight<dist[v]){dist[v]=dist[u]+weight;// If weight is 0, push to front (higher priority)// If weight is 1, push to back (lower priority)if(weight==0)dq.push_front(v);elsedq.push_back(v);}}}returndist;}intmain(){intn=9,src=0;vector<vector<int>>edges={{0,1,0},{0,7,1},{1,2,1},{1,7,1},{2,3,0},{2,5,0},{2,8,1},{3,4,1},{3,5,1},{4,5,1},{5,6,1},{6,7,1},{7,8,1}};// Create adjacency list representation of the graphvector<vector<vector<int>>>adj(n);for(auto&edge:edges){intu=edge[0];intv=edge[1];intw=edge[2];adj[u].push_back({v,w});adj[v].push_back({u,w});}vector<int>res=minDist(n,src,adj);for(inti=0;i<n;i++){cout<<res[i]<<" ";}cout<<endl;return0;}
Java
importjava.util.ArrayDeque;importjava.util.ArrayList;importjava.util.Deque;importjava.util.List;publicclassMain{publicstaticint[]minDist(intn,intsrc,List<List<int[]>>adj){// Initialize distances to infinityint[]dist=newint[n];for(inti=0;i<n;i++){dist[i]=Integer.MAX_VALUE;}dist[src]=0;// Use deque for 0-1 BFSDeque<Integer>dq=newArrayDeque<>();dq.add(src);while(!dq.isEmpty()){intu=dq.poll();// Process all adjacent verticesfor(int[]edge:adj.get(u)){intv=edge[0];intweight=edge[1];// If we can improve the distanceif(dist[u]+weight<dist[v]){dist[v]=dist[u]+weight;// If weight is 0, push to front (higher priority)// If weight is 1, push to back (lower priority)if(weight==0){dq.addFirst(v);}else{dq.addLast(v);}}}}returndist;}publicstaticvoidmain(String[]args){intn=9;intsrc=0;int[][]edges={{0,1,0},{0,7,1},{1,2,1},{1,7,1},{2,3,0},{2,5,0},{2,8,1},{3,4,1},{3,5,1},{4,5,1},{5,6,1},{6,7,1},{7,8,1}};// Create adjacency list representation of the graphList<List<int[]>>adj=newArrayList<>();for(inti=0;i<n;i++){adj.add(newArrayList<>());}for(int[]edge:edges){intu=edge[0];intv=edge[1];intw=edge[2];adj.get(u).add(newint[]{v,w});adj.get(v).add(newint[]{u,w});}int[]res=minDist(n,src,adj);for(inti=0;i<n;i++){System.out.print(res[i]+" ");}System.out.println();}}
Python
fromcollectionsimportdequeimportsysdefminDist(n,src,adj):# Initialize distances to infinitydist=[sys.maxsize]*ndist[src]=0# Use deque for 0-1 BFSdq=deque()dq.append(src)whiledq:u=dq.popleft()# Process all adjacent verticesforedgeinadj[u]:v=edge[0]weight=edge[1]# If we can improve the distanceifdist[u]+weight<dist[v]:dist[v]=dist[u]+weight# If weight is 0, push to front (higher priority)# If weight is 1, push to back (lower priority)ifweight==0:dq.appendleft(v)else:dq.append(v)returndistdefmain():n=9src=0edges=[(0,1,0),(0,7,1),(1,2,1),(1,7,1),(2,3,0),(2,5,0),(2,8,1),(3,4,1),(3,5,1),(4,5,1),(5,6,1),(6,7,1),(7,8,1)]# Create adjacency list representation of the graphadj=[[]for_inrange(n)]foru,v,winedges:adj[u].append((v,w))adj[v].append((u,w))res=minDist(n,src,adj)foriinrange(n):print(res[i],end=' ')print()if__name__=="__main__":main()
C#
usingSystem;usingSystem.Collections.Generic;classProgram{staticintMAX_VALUE=int.MaxValue;staticList<int>minDist(intn,intsrc,List<Tuple<int,int>>[]adj){// Initialize distances to infinityint[]dist=newint[n];Array.Fill(dist,MAX_VALUE);dist[src]=0;// Use Queue for 0-1 BFSQueue<int>dq=newQueue<int>();dq.Enqueue(src);while(dq.Count>0){intu=dq.Dequeue();// Process all adjacent verticesforeach(varedgeinadj[u]){intv=edge.Item1;intweight=edge.Item2;// If we can improve the distanceif(dist[u]+weight<dist[v]){dist[v]=dist[u]+weight;// If weight is 0, push to front (higher priority)// If weight is 1, push to back (lower priority)if(weight==0){dq.Enqueue(v);}else{dq.Enqueue(v);}}}}returnnewList<int>(dist);}staticvoidMain(){intn=9;intsrc=0;varedges=newList<Tuple<int,int,int>>{newTuple<int,int,int>(0,1,0),newTuple<int,int,int>(0,7,1),newTuple<int,int,int>(1,2,1),newTuple<int,int,int>(1,7,1),newTuple<int,int,int>(2,3,0),newTuple<int,int,int>(2,5,0),newTuple<int,int,int>(2,8,1),newTuple<int,int,int>(3,4,1),newTuple<int,int,int>(3,5,1),newTuple<int,int,int>(4,5,1),newTuple<int,int,int>(5,6,1),newTuple<int,int,int>(6,7,1),newTuple<int,int,int>(7,8,1)};// Create adjacency list representation of the graphvaradj=newList<Tuple<int,int>>[n];for(inti=0;i<n;i++){adj[i]=newList<Tuple<int,int>>();}foreach(varedgeinedges){adj[edge.Item1].Add(newTuple<int,int>(edge.Item2,edge.Item3));adj[edge.Item2].Add(newTuple<int,int>(edge.Item1,edge.Item3));}varres=minDist(n,src,adj);foreach(vardinres){Console.Write(d+" ");}Console.WriteLine();}}
JavaScript
constMAX_VALUE=Number.MAX_VALUE;constminDist=(n,src,adj)=>{// Initialize distances to infinityconstdist=Array(n).fill(MAX_VALUE);dist[src]=0;// Use Queue for 0-1 BFSconstdq=[src];while(dq.length>0){constu=dq.shift();// Process all adjacent verticesfor(constedgeofadj[u]){constv=edge[0];constweight=edge[1];// If we can improve the distanceif(dist[u]+weight<dist[v]){dist[v]=dist[u]+weight;// If weight is 0, push to front (higher priority)// If weight is 1, push to back (lower priority)if(weight===0){dq.unshift(v);}else{dq.push(v);}}}}returndist;};constmain=()=>{constn=9;constsrc=0;constedges=[[0,1,0],[0,7,1],[1,2,1],[1,7,1],[2,3,0],[2,5,0],[2,8,1],[3,4,1],[3,5,1],[4,5,1],[5,6,1],[6,7,1],[7,8,1]];// Create adjacency list representation of the graphconstadj=Array.from({length:n},()=>[]);for(constedgeofedges){adj[edge[0]].push([edge[1],edge[2]]);adj[edge[1]].push([edge[0],edge[2]]);}constres=minDist(n,src,adj);console.log(res.join(' '));};main();