Workspace Spiral Matrix
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Spiral Matrix visualizer

Learn Spiral Matrix with a step-by-step Arrays visualizer, JavaScript source code and a worked example. Practice optimization and matrix.

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 / 10Execution step
Reference example · JavaScript
Inspect reference input
[
  [
    1,
    2,
    3
  ],
  [
    4,
    5,
    6
  ],
  [
    7,
    8,
    9
  ]
]

Algorithm source

JavaScript reference implementation · highlighted trace statement
const solve = (m,s)=>{
let t=0,b=m.length-1,l=0,r=m[0].length-1,o=[];
function p(i,j){
o.push(m[i][j]);
s("Visit cell "+i+","+j,{
Matrix:m,Spiral:o
})
}
while(t<=b&&l<=r){
for(let j=l;
j<=r;
j++)p(t,j);
t++;
for(let i=t;
i<=b;
i++)p(i,r);
r--;
if(t<=b){
for(let j=r;
j>=l;
j--)p(b,j);
b--
}
if(l<=r){
for(let i=b;
i>=t;
i--)p(i,l);
l++
}
}
return o
};

Execution canvas

Active Changed
STEP 1

Visit cell 0,0

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

Matrix3 rows
Spiral1 items
Keyboard: Space to play · Left / Right to stepExplore next problem

Worked example and algorithm walkthrough

Topic: Arrays · Optimization and matrix

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

[
  [
    1,
    2,
    3
  ],
  [
    4,
    5,
    6
  ],
  [
    7,
    8,
    9
  ]
]

Execution steps

  1. Visit cell 0,0
  2. Visit cell 0,1
  3. Visit cell 0,2
  4. Visit cell 1,2
  5. Visit cell 2,2
  6. Visit cell 2,1
  7. Visit cell 2,0
  8. Visit cell 1,0
  9. Visit cell 1,1

Computed output

[
  1,
  2,
  3,
  6,
  9,
  8,
  7,
  4,
  5
]
JavaScript reference implementation
const solve = (m,s)=>{
  let t=0,b=m.length-1,l=0,r=m[0].length-1,o=[];
  function p(i,j){
    o.push(m[i][j]);
    s("Visit cell "+i+","+j,{
      Matrix:m,Spiral:o
    })
  }
  while(t<=b&&l<=r){
    for(let j=l;
    j<=r;
    j++)p(t,j);
    t++;
    for(let i=t;
    i<=b;
    i++)p(i,r);
    r--;
    if(t<=b){
      for(let j=r;
      j>=l;
      j--)p(b,j);
      b--
    }
    if(l<=r){
      for(let i=b;
      i>=t;
      i--)p(i,l);
      l++
    }
  }
  return o
};

Continue learning

Practice related DSA questions in the same topic.