Learn Find Eventual Safe States with a step-by-step Graphs visualizer, JavaScript source code and a worked example. Practice topological sorting and shortest paths.
INTERACTIVE EXECUTION STUDIO
LEARN BY DOING
Predict. Execute. Understand.
Follow the source code, inspect live state changes, and predict the next operation before revealing it.
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.
const solve = (a,s)=>{
let d=a.map(r=>r.length),rev=a.map(()=>[]);
a.forEach((r,i)=>r.forEach(v=>rev[v].push(i)));
let q=d.map((x,i)=>x?null:i).filter(x=>x!==null),o=[];
while(q.length){
let u=q.shift();
o.push(u);
for(let v of rev[u])if(--d[v]===0)q.push(v);
s("Remove terminal or newly safe vertex",{
Graph:a,Outdegree:d,Queue:q,Safe:o
})
}
return o.sort((a,b)=>a-b)
};