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
- Visit cell 0,0
- Visit cell 0,1
- Visit cell 0,2
- Visit cell 1,2
- Visit cell 2,2
- Visit cell 2,1
- Visit cell 2,0
- Visit cell 1,0
- 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
};