Worked example and algorithm walkthrough
Topic: Graphs · MST, DSU and advanced
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": 5,
"edges": [
[
0,
1
],
[
1,
2
],
[
2,
0
],
[
1,
3
],
[
3,
4
]
],
"cut": false
}Execution steps
- Compare discovery and low-link values
Computed output
[
[
1,
3
],
[
3,
4
]
]JavaScript reference implementation
const solve = ({
n,edges,cut
},s)=>{
let a=adj(n,edges),tin=Array(n).fill(-1),low=tin.slice(),time=0,bridges=[],points=new Set;
function f(u,p){
tin[u]=low[u]=time++;
let children=0;
for(let [v] of a[u]){
if(v===p)continue;
if(tin[v]>=0)low[u]=Math.min(low[u],tin[v]);
else{
children++;
f(v,u);
low[u]=Math.min(low[u],low[v]);
if(low[v]>tin[u])bridges.push([Math.min(u,v),Math.max(u,v)]);
if(p!==-1&&low[v]>=tin[u])points.add(u)
}
s("Compare discovery and low-link values",{
Edges:edges,Discovery:tin,Low:low,Current:[u,v],Bridges:bridges,Articulation:[...points]
})
}
if(p===-1&&children>1)points.add(u)
}
for(let i=0;
i<n;
i++)if(tin[i]<0)f(i,-1);
return cut?[...points].sort((a,b)=>a-b):bridges.sort((a,b)=>a[0]-b[0]||a[1]-b[1])
};
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]];