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": 3,
"m": 3,
"ops": [
[
0,
0
],
[
0,
1
],
[
1,
2
],
[
2,
1
],
[
1,
1
]
]
}Execution steps
- Add land and union adjacent islands
Computed output
[ 1, 1, 2, 3, 1 ]
JavaScript reference implementation
const solve = ({
n,m,ops
},s)=>{
let d=dsu(n*m),a=Array.from({
length:n
},()=>Array(m).fill(0)),c=0,o=[];
for(let [i,j] of ops){
if(!a[i][j]){
a[i][j]=1;
c++;
for(let [x,y] of dirs){
let r=i+x,k=j+y;
if(a[r]?.[k]&&d.union(i*m+j,r*m+k))c--
}
}
o.push(c);
s("Add land and union adjacent islands",{
Grid:a,Parents:d.p,Counts:o,Cell:[i,j]
})
}
return o
};
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]];