You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
🔥 Find if Path Exists in Graph 🔥 || 3 Approaches || Simple Fast and Easy || with Explanation
Solution - 1 Union Find Algorithm
Union Find Implementation
classUnionFind {
// parent of nodelatefinalList<int> parent;
// rank of disjoint setlatefinalList<int> rank;
// number of disjoint setlateint count;
UnionFind(int n) {
count = n;
parent =List.filled(n, 0);
rank =List.filled(n, 0);
for (int i =0; i < n; i++) {
// every node is itself
parent[i] = i;
// every node init rank is one
rank[i] =1;
}
}
introot(int p) {
while (parent[p] != p) {
// compress path
parent[p] = parent[parent[p]];
p = parent[p];
}
return p;
}
intcounting() {
return count;
}
boolfind(int p, int q) {
returnroot(p) ==root(q);
}
boolunion(int p, int q) {
int rootP =root(p);
int rootQ =root(q);
if (rootP == rootQ) {
returnfalse;
}
if (rank[rootP] < rank[rootQ]) {
parent[rootP] = rootQ;
rank[rootQ] += rank[rootP];
} else {
parent[rootQ] = rootP;
rank[rootP] += rank[rootQ];
}
count--;
returntrue;
}
}
Final Code
classSolution {
boolvalidPath(int n, List<List<int>> edges, int source, int destination) {
UnionFind uf =UnionFind(n);
for (List<int> edge in edges) {
// connect two node
uf.union(edge[0], edge[1]);
}
return uf.find(source, destination);
}
}
Solution - 2
classSolution {
List<int> parent = [];
intfindParent(int node) {
return parent[node] == node
? node
: (parent[node] =findParent(parent[node]));
}
voidmakeSameGroup(int u, int v) {
int pu =findParent(u);
int pv =findParent(v);
parent[pu] = pv;
}
boolvalidPath(int n, List<List<int>> edges, int source, int destination) {
// resizing an array
parent =List.filled(n, 0);
for (int i =0; i < n; i++) parent[i] = i;
for (List<int> e in edges) {
makeSameGroup(e[0], e[1]);
}
returnfindParent(source) ==findParent(destination);
}
}
Solution - 3 DFS
classSolution {
bool found =false;
voiddfs(Map<int, List<int>> graph, List<bool> visited, int start, int end) {
if (visited[start] || found) return;
visited[start] =true;
//when we found and neighbor which is equal to end point inside the recursion, voooleeey! break and return the truefor (int nei in graph[start] ?? []) {
if (nei == end) {
found =true;
break;
}
if (!visited[nei])
dfs(graph, visited, nei, end); //otherwise deep dig again!
}
}
boolvalidPath(int n, List<List<int>> edges, int source, int destination) {
if (source == destination) returntrue;
HashMap<int, List<int>> graph =HashMap();
List<bool> visited =List.filled(n, false);
for (int i =0; i < n; i++) graph[i] = [];
//construct graph, add bidirectional vertexfor (List<int> edge in edges) {
graph[edge[0]]?.add(edge[1]);
graph[edge[1]]?.add(edge[0]);
}
//start dfs from start pointdfs(graph, visited, source, destination);
return found;
}
}