[Expected Approach - 1] Using DFS - O(V+E) Time and O(V+E) Auxiliary Space
The idea is to explore all the vertices reachable from the starting vertex u using the Depth First Search (DFS) algorithm. During the traversal, if the target vertex v is found, we can conclude that a path exists between u and v; otherwise, no path exists.
C++
//Driver Code Starts#include<iostream>#include<vector>usingnamespacestd;//Driver Code Ends// DFS to check if a path exists from curr to destbooldfs(intcurr,intdest,vector<vector<int>>&adj,vector<bool>&visited){// already exploredif(visited[curr])returnfalse;// destination reachedif(curr==dest)returntrue;visited[curr]=true;for(intneighbor:adj[curr]){if(!visited[neighbor]&&dfs(neighbor,dest,adj,visited)){// path foundreturntrue;}}// no path foundreturnfalse;}// Function to check if a path exists between u and vboolcheckPath(vector<vector<int>>&adj,intu,intv){vector<bool>visited(adj.size(),false);returndfs(u,v,adj,visited);}//Driver Code Startsintmain(){vector<vector<int>>adj={{2,3},{2},{0,1},{0},{5},{4}};intu=2,v=3;cout<<(checkPath(adj,u,v)?"true":"false");return0;}//Driver Code Ends
Java
//Driver Code Startsimportjava.util.ArrayList;publicclassGFG{//Driver Code Ends// DFS to check if path exists from curr to deststaticbooleandfs(intcurr,intdest,ArrayList<ArrayList<Integer>>adj,boolean[]visited){// already exploredif(visited[curr])returnfalse;// destination reachedif(curr==dest)returntrue;visited[curr]=true;for(intneighbor:adj.get(curr)){if(!visited[neighbor]&&dfs(neighbor,dest,adj,visited)){// path foundreturntrue;}}// no path foundreturnfalse;}// Function to check path between u and vstaticbooleancheckPath(ArrayList<ArrayList<Integer>>adj,intu,intv){boolean[]visited=newboolean[adj.size()];returndfs(u,v,adj,visited);}//Driver Code Starts// Function to add undirected edgestaticvoidaddEdge(ArrayList<ArrayList<Integer>>adj,intu,intv){adj.get(u).add(v);adj.get(v).add(u);}publicstaticvoidmain(String[]args){intV=6;ArrayList<ArrayList<Integer>>adj=newArrayList<>();for(inti=0;i<V;i++)adj.add(newArrayList<>());addEdge(adj,0,2);addEdge(adj,0,3);addEdge(adj,1,2);addEdge(adj,4,5);intu=2,v=3;System.out.println(checkPath(adj,u,v)?"true":"false");}}//Driver Code Ends
//Driver Code StartsusingSystem;usingSystem.Collections.Generic;classGFG{//Driver Code Ends// DFS to check if path exists from curr to deststaticbooldfs(intcurr,intdest,List<List<int>>adj,bool[]visited){// already exploredif(visited[curr])returnfalse;// destination reachedif(curr==dest)returntrue;visited[curr]=true;foreach(intneighborinadj[curr]){if(!visited[neighbor]&&dfs(neighbor,dest,adj,visited)){// path foundreturntrue;}}// no path foundreturnfalse;}// Function to check path between u and vstaticboolcheckPath(List<List<int>>adj,intu,intv){bool[]visited=newbool[adj.Count];returndfs(u,v,adj,visited);}//Driver Code Starts// Function to add undirected edgestaticvoidaddEdge(List<List<int>>adj,intu,intv){adj[u].Add(v);adj[v].Add(u);}staticvoidMain(){intV=6;List<List<int>>adj=newList<List<int>>();for(inti=0;i<V;i++)adj.Add(newList<int>());addEdge(adj,0,2);addEdge(adj,0,3);addEdge(adj,1,2);addEdge(adj,4,5);intu=2,v=3;Console.WriteLine(checkPath(adj,u,v)?"true":"false");}}//Driver Code Ends
[Expected Approach - 2] Using BFS - O(V+E) Time and O(V) Auxiliary Space
The idea is to explore all the vertices reachable from the starting vertex u using the Breadth First Search (BFS) algorithm. During the traversal, if the target vertex v is encountered, we can conclude that a path exists between u and v; otherwise, no path exists.
C++
//Driver Code Starts#include<iostream>#include<vector>#include<queue>usingnamespacestd;//Driver Code Ends// BFS to check if a path exists from src to destboolbfs(intsrc,intdest,vector<vector<int>>&adj){vector<bool>visited(adj.size(),false);queue<int>q;visited[src]=true;q.push(src);while(!q.empty()){intcurr=q.front();q.pop();// destination reachedif(curr==dest)returntrue;// visit all unvisited neighborsfor(intneighbor:adj[curr]){if(!visited[neighbor]){visited[neighbor]=true;q.push(neighbor);}}}// no path foundreturnfalse;}// Function to check if a path exists between u and vboolcheckPath(vector<vector<int>>&adj,intu,intv){returnbfs(u,v,adj);}//Driver Code Startsintmain(){vector<vector<int>>adj={{2,3},{2},{0,1},{0},{5},{4}};intu=2,v=3;cout<<(checkPath(adj,u,v)?"true":"false")<<endl;return0;}//Driver Code Ends
Java
//Driver Code Startsimportjava.util.ArrayList;importjava.util.LinkedList;importjava.util.Queue;publicclassGFG{//Driver Code Ends// BFS to check if a path exists from src to deststaticbooleanbfs(intsrc,intdest,ArrayList<ArrayList<Integer>>adj){boolean[]visited=newboolean[adj.size()];Queue<Integer>q=newLinkedList<>();visited[src]=true;q.offer(src);while(!q.isEmpty()){// remove the front vertexintcurr=q.poll();// destination reachedif(curr==dest)returntrue;// visit all unvisited neighborsfor(intneighbor:adj.get(curr)){if(!visited[neighbor]){visited[neighbor]=true;q.offer(neighbor);}}}// no path foundreturnfalse;}// Function to check if a path exists between u and vstaticbooleancheckPath(ArrayList<ArrayList<Integer>>adj,intu,intv){returnbfs(u,v,adj);}//Driver Code Starts// Function to add undirected edgestaticvoidaddEdge(ArrayList<ArrayList<Integer>>adj,intu,intv){adj.get(u).add(v);adj.get(v).add(u);}publicstaticvoidmain(String[]args){intV=6;ArrayList<ArrayList<Integer>>adj=newArrayList<>();for(inti=0;i<V;i++)adj.add(newArrayList<>());addEdge(adj,0,2);addEdge(adj,0,3);addEdge(adj,1,2);addEdge(adj,4,5);intu=2,v=3;System.out.println(checkPath(adj,u,v)?"true":"false");}}//Driver Code Ends
Python
#Driver Code Startsfromcollectionsimportdeque#Driver Code Ends# BFS to check if a path exists from src to destdefbfs(src,dest,adj):visited=[False]*len(adj)q=deque()visited[src]=Trueq.append(src)whileq:curr=q.popleft()# destination reachedifcurr==dest:returnTrue# visit all unvisited neighborsforneighborinadj[curr]:ifnotvisited[neighbor]:visited[neighbor]=Trueq.append(neighbor)# no path foundreturnFalse# Function to check if a path exists between u and vdefcheckPath(adj,u,v):returnbfs(u,v,adj)#Driver Code Startsif__name__=="__main__":adj=[[2,3],[2],[0,1],[0],[5],[4]]u,v=2,3print("true"ifcheckPath(adj,u,v)else"false")#Driver Code Ends
C#
//Driver Code StartsusingSystem;usingSystem.Collections.Generic;classGFG{//Driver Code Ends// BFS to check if a path exists from src to deststaticboolbfs(intsrc,intdest,List<List<int>>adj){bool[]visited=newbool[adj.Count];Queue<int>q=newQueue<int>();visited[src]=true;q.Enqueue(src);while(q.Count>0){// remove the front vertexintcurr=q.Dequeue();// destination reachedif(curr==dest)returntrue;// visit all unvisited neighborsforeach(intneighborinadj[curr]){if(!visited[neighbor]){visited[neighbor]=true;q.Enqueue(neighbor);}}}// no path foundreturnfalse;}// Function to check if a path exists between u and vstaticboolcheckPath(List<List<int>>adj,intu,intv){returnbfs(u,v,adj);}//Driver Code Starts// Function to add undirected edgestaticvoidaddEdge(List<List<int>>adj,intu,intv){adj[u].Add(v);adj[v].Add(u);}staticvoidMain(){intV=6;List<List<int>>adj=newList<List<int>>();for(inti=0;i<V;i++)adj.Add(newList<int>());addEdge(adj,0,2);addEdge(adj,0,3);addEdge(adj,1,2);addEdge(adj,4,5);intu=2,v=3;Console.WriteLine(checkPath(adj,u,v)?"true":"false");}}//Driver Code Ends
JavaScript
//Driver Code StartsconstDenque=require("denque");//Driver Code Ends// BFS to check if a path exists from src to destfunctionbfs(adj,src,dest){constvisited=newArray(adj.length).fill(false);constq=newDenque();visited[src]=true;q.push(src);while(!q.isEmpty()){// remove the front vertexconstcurr=q.shift();// destination reachedif(curr===dest)returntrue;// Visit all unvisited // neighbours of current nodefor(letneighborofadj[curr]){if(!visited[neighbor]){visited[neighbor]=true;q.push(neighbor);}}}// no path foundreturnfalse;}// Function to check if a path exists between u and vfunctioncheckPath(adj,u,v){returnbfs(adj,u,v);}//Driver Code Starts// Driver codeconstadj=[[2,3],[2],[0,1],[0],[5],[4]];constu=2,v=3;constpathExists=checkPath(adj,u,v);console.log(pathExists?"true":"false");//Driver Code Ends
Output
true
[Alternate Approach] Using DSU - O(V) Time and O(V) Space
In this approach, we check if both vertices exists in the same component. If both of the vertices are in the same component, then there is always a path between them, otherwise there is no path between them.
To implement this approach, we are using DSU algorithm. To read more about DSU, refer to this article.
C++
//Driver Code Starts#include<iostream>#include<vector>usingnamespacestd;//Driver Code Ends// DSU classclassDSU{vector<int>parent;public:DSU(intn){parent.resize(n);// Each node is its own parent initiallyfor(inti=0;i<n;i++){parent[i]=i;}}// Find with path compressionintfindParent(intu){if(u==parent[u])returnu;returnparent[u]=findParent(parent[u]);}// Union the sets of u and vvoidunite(intu,intv){intpu=findParent(u);intpv=findParent(v);if(pu==pv)return;parent[pu]=pv;}};// function to check if two nodes are in the same component using DSUbooldsu(vector<vector<int>>&adj,intsrc,intdest){intV=adj.size();DSUdsuObj(V);for(inti=0;i<V;i++){for(intnext:adj[i]){dsuObj.unite(i,next);}}returndsuObj.findParent(src)==dsuObj.findParent(dest);}// Function to check path between u and vboolcheckPath(vector<vector<int>>&adj,intu,intv){returndsu(adj,u,v);}//Driver Code Startsintmain(){vector<vector<int>>adj={{2,3},{2},{0,1},{0},{5},{4}};intu=2,v=3;boolpathExists=checkPath(adj,u,v);cout<<(pathExists?"true":"false")<<endl;return0;}//Driver Code Ends
Java
//Driver Code Startsimportjava.util.ArrayList;classGFG{//Driver Code Ends// DSU classstaticclassDSU{int[]parent;DSU(intn){// Each node is its own parent initiallyparent=newint[n];for(inti=0;i<n;i++){parent[i]=i;}}// Find with path compressionintfindParent(intu){if(parent[u]==u)returnu;parent[u]=findParent(parent[u]);returnparent[u];}// Union the sets of u and vvoidunite(intu,intv){intpu=findParent(u);intpv=findParent(v);if(pu==pv)return;parent[pu]=pv;}}// function to check if two nodes are in the same component using DSUstaticbooleandsu(ArrayList<ArrayList<Integer>>adj,intsrc,intdest){intV=adj.size();DSUdsuObj=newDSU(V);for(inti=0;i<V;i++){for(intnext:adj.get(i)){dsuObj.unite(i,next);}}returndsuObj.findParent(src)==dsuObj.findParent(dest);}// Function to check path between u and vstaticbooleancheckPath(ArrayList<ArrayList<Integer>>adj,intu,intv){returndsu(adj,u,v);}//Driver Code Starts// Function to add undirected edgestaticvoidaddEdge(ArrayList<ArrayList<Integer>>adj,intu,intv){adj.get(u).add(v);adj.get(v).add(u);}publicstaticvoidmain(String[]args){intV=6;ArrayList<ArrayList<Integer>>adj=newArrayList<>();for(inti=0;i<V;i++)adj.add(newArrayList<>());addEdge(adj,0,2);addEdge(adj,0,3);addEdge(adj,1,2);addEdge(adj,4,5);intu=2,v=3;System.out.println(checkPath(adj,u,v)?"true":"false");}}//Driver Code Ends
Python
# DSU classclassDSU:def__init__(self,n):# Each node is its own parent initiallyself.parent=list(range(n))# Find with path compressiondeffindParent(self,u):ifself.parent[u]==u:returnuself.parent[u]=self.findParent(self.parent[u])returnself.parent[u]# Union the sets of u and vdefunite(self,u,v):pu=self.findParent(u)pv=self.findParent(v)ifpu==pv:returnself.parent[pu]=pv# function to check if two nodes are in the same component using DSUdefdsu(adj,src,dest):V=len(adj)dsuObj=DSU(V)foriinrange(V):fornext_nodeinadj[i]:dsuObj.unite(i,next_node)returndsuObj.findParent(src)==dsuObj.findParent(dest)# Function to check path between u and vdefcheckPath(adj,u,v):returndsu(adj,u,v)#Driver Code Startsif__name__=="__main__":adj=[[2,3],[2],[0,1],[0],[5],[4]]u,v=2,3pathExists=checkPath(adj,u,v)print("true"ifpathExistselse"false")#Driver Code Ends
C#
//Driver Code StartsusingSystem;usingSystem.Collections.Generic;classGFG{//Driver Code Ends// DSU classclassDSU{int[]parent;publicDSU(intn){// Each node is its own parent initiallyparent=newint[n];for(inti=0;i<n;i++)parent[i]=i;}// Find with path compressionpublicintfindParent(intu){if(parent[u]==u)returnu;parent[u]=findParent(parent[u]);returnparent[u];}// Union the sets of u and vpublicvoidunite(intu,intv){intpu=findParent(u);intpv=findParent(v);if(pu==pv)return;parent[pu]=pv;}}// function to check if two nodes are in the same component using DSUstaticbooldsu(List<List<int>>adj,intsrc,intdest){intV=adj.Count;DSUdsuObj=newDSU(V);for(inti=0;i<V;i++){foreach(intnextinadj[i])dsuObj.unite(i,next);}returndsuObj.findParent(src)==dsuObj.findParent(dest);}// Function to check path between u and vstaticboolcheckPath(List<List<int>>adj,intu,intv){returndsu(adj,u,v);}//Driver Code Starts// Function to add undirected edgestaticvoidaddEdge(List<List<int>>adj,intu,intv){adj[u].Add(v);adj[v].Add(u);}staticvoidMain(){intV=6;List<List<int>>adj=newList<List<int>>();for(inti=0;i<V;i++)adj.Add(newList<int>());addEdge(adj,0,2);addEdge(adj,0,3);addEdge(adj,1,2);addEdge(adj,4,5);intu=2,v=3;Console.WriteLine(checkPath(adj,u,v)?"true":"false");}}//Driver Code Ends
JavaScript
// DSU classclassDSU{constructor(n){// Each node is its own parent initiallythis.parent=Array.from({length:n},(_,i)=>i);}// Find with path compressionfindParent(u){if(this.parent[u]===u)returnu;this.parent[u]=this.findParent(this.parent[u]);returnthis.parent[u];}// Union the sets of u and vunite(u,v){constpu=this.findParent(u);constpv=this.findParent(v);if(pu===pv)return;this.parent[pu]=pv;}}// function to check if two nodes are in the same component using DSUfunctiondsu(adj,src,dest){constV=adj.length;constdsuObj=newDSU(V);for(leti=0;i<V;i++){for(letnextofadj[i]){dsuObj.unite(i,next);}}returndsuObj.findParent(src)===dsuObj.findParent(dest);}// Function to check path between u and vfunctioncheckPath(adj,u,v){returndsu(adj,u,v);}//Driver Code Starts// Driver Codeconstadj=[[2,3],[2],[0,1],[0],[5],[4]];constu=2,v=3;constpathExists=checkPath(adj,u,v);console.log(pathExists?"true":"false");//Driver Code Ends