function PrintMatrixInSpiralForm(matrix) {
if (matrix == null || matrix.length == 0) {
return;
}
let top = 0;
let bottom = matrix.length - 1;
let left = 0;
let right = matrix[0].length - 1;
while (true) {
if (left > right) {
break;
}
// top row
for (let i = left; i <= right; i++) {
console.log(matrix[top][i]);
}
console.log();
top++; // next row
// next row
if (top > bottom) {
break;
}
// right column
for (let i = top; i <= bottom; i++) {
console.log(matrix[i][right]);
}
console.log();
right--; // previous column
// previous column
if (left > right) {
break;
}
// bottom row
for (let i = right; i >= left; i--) {
console.log(matrix[bottom][i]);
}
console.log();
bottom--; // previous row
// previous row
if (top > bottom) {
break;
}
// left column
for (let i = bottom; i >= top; i--) {
console.log(matrix[i][left]);
}
console.log();
left++; // next column
}
}
const matrix = [[1, 2, 3, 4, 100],
[5, 6, 7, 8, 200],
[9, 10, 11, 12, 300],
[13, 14, 15, 16, 400]];
PrintMatrixInSpiralForm(matrix);
/*
run:
1
2
3
4
8
12
16
15
14
13
9
5
6
7
11
10
*/