Workspace Shortest Path In Binary Matrix
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Shortest Path in Binary Matrix visualizer

Learn Shortest Path in Binary Matrix 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 / 3Execution step
Reference example · JavaScript
Inspect reference input
[
  [
    0,
    1
  ],
  [
    1,
    0
  ]
]

Algorithm source

JavaScript reference implementation · highlighted trace statement
const solve = (a,s)=>{
let n=a.length,d=a.map(r=>r.map(()=>0)),q=[[0,0]];
if(a[0][0])return -1;
d[0][0]=1;
while(q.length){
let [i,j]=q.shift();
s("Visit next shortest cell",{
Grid:a,Distance:d,Queue:q,Cell:[i,j]
});
if(i===n-1&&j===n-1)return d[i][j];
for(let x=-1;
x<=1;
x++)for(let y=-1;
y<=1;
y++){
let r=i+x,c=j+y;
if(a[r]?.[c]===0&&!d[r][c]){
d[r][c]=d[i][j]+1;
q.push([r,c])
}
}
}
return -1
};

Execution canvas

Active Changed
STEP 1

Visit next shortest cell

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

Grid2 rows
Distance2 rows
Queue0 items

Empty at this step.

Cell2 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

[
  [
    0,
    1
  ],
  [
    1,
    0
  ]
]

Execution steps

  1. Visit next shortest cell

Computed output

2
JavaScript reference implementation
const solve = (a,s)=>{
  let n=a.length,d=a.map(r=>r.map(()=>0)),q=[[0,0]];
  if(a[0][0])return -1;
  d[0][0]=1;
  while(q.length){
    let [i,j]=q.shift();
    s("Visit next shortest cell",{
      Grid:a,Distance:d,Queue:q,Cell:[i,j]
    });
    if(i===n-1&&j===n-1)return d[i][j];
    for(let x=-1;
    x<=1;
    x++)for(let y=-1;
    y<=1;
    y++){
      let r=i+x,c=j+y;
      if(a[r]?.[c]===0&&!d[r][c]){
        d[r][c]=d[i][j]+1;
        q.push([r,c])
      }
    }
  }
  return -1
};

Continue learning

Practice related DSA questions in the same topic.