Workspace Bellman Ford
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Bellman Ford visualizer

Learn Bellman Ford 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.

1 / 13Execution step
Reference example · JavaScript
Inspect reference input
{
  "n": 4,
  "edges": [
    [
      0,
      1,
      4
    ],
    [
      0,
      2,
      5
    ],
    [
      1,
      2,
      -2
    ],
    [
      2,
      3,
      3
    ]
  ]
}

Algorithm source

JavaScript reference implementation · highlighted trace statement
const solve = ({
n,edges
},s)=>{
let d=Array(n).fill(Infinity);
d[0]=0;
for(let i=1;
i<n;
i++)for(let [u,v,w] of edges){
if(d[u]+w<d[v])d[v]=d[u]+w;
s("Relax edge on pass "+i,{
Edges:edges,Distance:d.map(x=>Number.isFinite(x)?x:null),Current:[u,v]
})
}
if(edges.some(([u,v,w])=>d[u]+w<d[v]))return [-1];
return d.map(x=>Number.isFinite(x)?x:null)
};

Execution canvas

Active Changed
STEP 1

Relax edge on pass 1

Inspect the highlighted code and the state below. Click individual cells or nodes to see their values.

Edges4 rows
45-230123Select a node to inspect its connections.
Distance4 items
Current2 items
Keyboard: Space to play · Left / Right to stepExplore next problem

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,
      4
    ],
    [
      0,
      2,
      5
    ],
    [
      1,
      2,
      -2
    ],
    [
      2,
      3,
      3
    ]
  ]
}

Execution steps

  1. Relax edge on pass 1
  2. Relax edge on pass 2
  3. Relax edge on pass 3

Computed output

[
  0,
  4,
  2,
  5
]
JavaScript reference implementation
const solve = ({
  n,edges
},s)=>{
  let d=Array(n).fill(Infinity);
  d[0]=0;
  for(let i=1;
  i<n;
  i++)for(let [u,v,w] of edges){
    if(d[u]+w<d[v])d[v]=d[u]+w;
    s("Relax edge on pass "+i,{
      Edges:edges,Distance:d.map(x=>Number.isFinite(x)?x:null),Current:[u,v]
    })
  }
  if(edges.some(([u,v,w])=>d[u]+w<d[v]))return [-1];
  return d.map(x=>Number.isFinite(x)?x:null)
};

Continue learning

Practice related DSA questions in the same topic.