/*
Spiral traversal of a matrix using a recursive solution.
The idea:
- At each recursive step, peel off one "layer" of the matrix:
1. Top row (left → right)
2. Right column (top → bottom)
3. Bottom row (right → left)
4. Left column (bottom → top)
- Then shrink the boundaries inward and recurse.
- Stop when boundaries cross.
*/
const spiral_recursively_traverse_matrix = (matrix) => {
// Defensive check: empty matrix
if (!matrix.length || !matrix[0].length) return [];
// Helper function performing the recursion
const recurse = (top, bottom, left, right, result) => {
// Base case: boundaries crossed → no more layers
if (top > bottom || left > right) return result;
// 1. Traverse top row
for (let col = left; col <= right; col++) {
result.push(matrix[top][col]);
}
// 2. Traverse right column
for (let row = top + 1; row <= bottom; row++) {
result.push(matrix[row][right]);
}
// 3. Traverse bottom row (only if top < bottom)
if (top < bottom) {
for (let col = right - 1; col >= left; col--) {
result.push(matrix[bottom][col]);
}
}
// 4. Traverse left column (only if left < right)
if (left < right) {
for (let row = bottom - 1; row > top; row--) {
result.push(matrix[row][left]);
}
}
// Recurse inward with updated boundaries
return recurse(top + 1, bottom - 1, left + 1, right - 1, result);
};
// Initial boundaries
const top = 0;
const bottom = matrix.length - 1;
const left = 0;
const right = matrix[0].length - 1;
// Start recursion
return recurse(top, bottom, left, right, []);
};
/*
run:
*/
const matrix = [
[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12],
[13, 14, 15, 16]
];
console.log(spiral_recursively_traverse_matrix(matrix));
/*
run:
[
1, 2, 3, 4, 8, 12,
16, 15, 14, 13, 9, 5,
6, 7, 11, 10
]
*/