A very simple solution for clockwise spiral matrix, self explanatory:
```
//spiral matrix
let m=[
[ 1, 2, 3, 4, 5, 6], //0,0 to 0,5
[ 7, 8, 9,10,11,12],
[13,14,15,16,17,18],
[19,20,21,22,23,24] //3,0 to 3,5
];
let top=0, left=0;
let bottom=m.length-1, right=m[0].length-1;
let direction="left"; // start from left towards right
while(true)
{
// First left to right → towards right
if(direction=="left")
{
for (let i=left;i<=right;i++)
console.log(m[top][i]);
top++;
if (top>bottom)
break;
else
direction="down";
}
// Second top to down ↓ : towards down
if(direction=="down")
{
for (let i=top;i<=bottom;i++)
console.log(m[i][right] );
right--;
if(left>right)
break;
else
direction="right";
}
//Third back from right to left ← towards left back
if(direction=="right")
{
for (let i=right;i>=left;i--)
console.log(m[bottom][i]);
bottom--;
if (top>bottom)
break;
else
direction="up";
}
// Fourth up ↑ up (from bottom to top)
if(direction=="up")
{
for (let i=bottom; i>=top; i--)
console.log(m[i][left]);
left++;
if (left>right)
break;
else
direction="left";
}
}
console.log("done")
```
Very simple, down to earth solution, self explanatory, clockwise spiral, written in JS but can be easily modified for any language
```
//spiral matrix
let m=[
[ 1, 2, 3, 4, 5, 6], //0,0 to 0,5
[ 7, 8, 9,10,11,12],
[13,14,15,16,17,18],
[19,20,21,22,23,24] //3,0 to 3,5
];
let top=0, left=0;
let bottom=m.length-1, right=m[0].length-1;
let direction="left"; // start from left towards right
while(true)
{
// First left to right → towards right
if(direction=="left")
{
for (let i=left;i<=right;i++)
console.log(m[top][i]);
top++;
if (top>bottom)
break;
else
direction="down";
}
// Second top to down ↓ : towards down
if(direction=="down")
{
for (let i=top;i<=bottom;i++)
console.log(m[i][right] );
right--;
if(left>right)
break;
else
direction="right";
}
//Third back from right to left ← towards left back
if(direction=="right")
{
for (let i=right;i>=left;i--)
console.log(m[bottom][i]);
bottom--;
if (top>bottom)
break;
else
direction="up";
}
// Fourth up ↑ up (from bottom to top)
if(direction=="up")
{
for (let i=bottom;i>=top;i--)
console.log(m[i][left]);
left++;
if (left>right)
break;
else
direction="left";
}
}
```