Worked example and algorithm walkthrough
Topic: Graphs · Topological sorting and shortest paths
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,
3
],
[
1,
2,
2
],
[
1,
3,
4
],
[
2,
3,
1
]
],
"threshold": 4,
"city": false
}Execution steps
- Allow intermediate vertex 0
- Allow intermediate vertex 1
- Allow intermediate vertex 2
- Allow intermediate vertex 3
Computed output
[
[
0,
3,
5,
6
],
[
3,
0,
2,
3
],
[
5,
2,
0,
1
],
[
6,
3,
1,
0
]
]JavaScript reference implementation
const solve = ({
n,edges,threshold,city
},s)=>{
let d=Array.from({
length:n
},(_,i)=>Array.from({
length:n
},(_,j)=>i===j?0:Infinity));
for(let [u,v,w] of edges)d[u][v]=d[v][u]=w;
for(let k=0;
k<n;
k++){
for(let i=0;
i<n;
i++)for(let j=0;
j<n;
j++)d[i][j]=Math.min(d[i][j],d[i][k]+d[k][j]);
s("Allow intermediate vertex "+k,{
Distance:d.map(r=>r.map(x=>Number.isFinite(x)?x:null)),Intermediate:[k]
})
}
if(!city)return d;
let counts=d.map((r,i)=>r.filter((v,j)=>i!==j&&v<=threshold).length);
s("Compare reachable city counts",{
Counts:counts
});
return counts.lastIndexOf(Math.min(...counts))
};