Worked example and algorithm walkthrough
Topic: Graphs · Traversal and connectivity
Follow the computed execution on the reference input. Advance one step at a time, inspect the changing values and compare your prediction with the final output.
Example input
{
"n": 4,
"edges": [
[
0,
1
],
[
1,
2
],
[
2,
1
],
[
2,
3
]
]
}Execution steps
- Mark vertex on recursion stack
- Back edge reaches active vertex
Computed output
true
JavaScript reference implementation
const solve = ({
n,edges
},s)=>{
let a=adj(n,edges,true),c=Array(n).fill(0);
function f(u){
c[u]=1;
s("Mark vertex on recursion stack",{
Edges:edges,States:c,Current:[u]
});
for(let [v] of a[u]){
if(c[v]===1){
s("Back edge reaches active vertex",{
Edges:edges,States:c,Current:[u,v]
});
return true
}
if(!c[v]&&f(v))return true
}
c[u]=2;
return false
}
for(let i=0;
i<n;
i++)if(!c[i]&&f(i))return true;
return false
};
function adj(n,edges,directed=false){
let a=Array.from({
length:n
},()=>[]);
for(let [u,v,w=1] of edges){
a[u].push([v,w]);
if(!directed)a[v].push([u,w])
}
return a
}
function dsu(n){
let p=Array.from({
length:n
},(_,i)=>i),z=p.map(()=>1);
function find(x){
while(p[x]!==x){
p[x]=p[p[x]];
x=p[x]
}
return x
}
function union(a,b){
a=find(a);
b=find(b);
if(a===b)return false;
if(z[a]<z[b])[a,b]=[b,a];
p[b]=a;
z[a]+=z[b];
return true
}
return {
p,z,find,union
}
}
const dirs=[[1,0],[-1,0],[0,1],[0,-1]];