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
[
[
1,
0
],
[
0,
1
]
]Execution steps
- Join distinct neighboring components
Computed output
3
JavaScript reference implementation
const solve = (a,s)=>{
let n=a.length,d=dsu(n*n);
for(let i=0;
i<n;
i++)for(let j=0;
j<n;
j++)if(a[i][j])for(let [x,y] of dirs){
let r=i+x,c=j+y;
if(a[r]?.[c])d.union(i*n+j,r*n+c)
}
let best=0;
for(let i=0;
i<n;
i++)for(let j=0;
j<n;
j++){
if(a[i][j]){
best=Math.max(best,d.z[d.find(i*n+j)]);
continue
}
let roots=new Set;
for(let [x,y] of dirs){
let r=i+x,c=j+y;
if(a[r]?.[c])roots.add(d.find(r*n+c))
}
let size=1+[...roots].reduce((v,r)=>v+d.z[r],0);
best=Math.max(best,size);
s("Join distinct neighboring components",{
Grid:a,Roots:[...roots],Candidate:[size],Best:[best],Cell:[i,j]
})
}
return best
};
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]];