Matrix Spiral
Receives an N×M matrix of integers and returns all of its elements in clockwise spiral order, starting from the top-left corner. It keeps four boundary pointers — top, bottom, left and right — and on each lap walks the top row left to right, the right column top to bottom, the bottom row right to left, and the left column bottom to top, shrinking the matching boundary inward after each side. It repeats until the boundaries cross, so every cell is visited exactly once. Returns a new array with the values in spiral order; an empty matrix yields an empty array, a single row is returned left to right, and a single column top to bottom.
Visualization
- Input
- Result
Algorithm code
// Matrix Spiral — a single pure function. Receives an N×M integer matrix and
// returns all of its elements in clockwise spiral order, starting from the
// top-left corner.
/**
* @param {number[][]} matrix - N×M matrix of integers
* @returns {number[]} elements of the matrix in clockwise spiral order
*/
export function spiralOrder(matrix) {
const result = [];
if (matrix.length === 0 || matrix[0].length === 0) {
return result;
}
let top = 0;
let bottom = matrix.length - 1;
let left = 0;
let right = matrix[0].length - 1;
while (top <= bottom && left <= right) {
for (let col = left; col <= right; col += 1) {
result.push(matrix[top][col]);
}
top += 1;
for (let row = top; row <= bottom; row += 1) {
result.push(matrix[row][right]);
}
right -= 1;
if (top <= bottom) {
for (let col = right; col >= left; col -= 1) {
result.push(matrix[bottom][col]);
}
bottom -= 1;
}
if (left <= right) {
for (let row = bottom; row >= top; row -= 1) {
result.push(matrix[row][left]);
}
left += 1;
}
}
return result;
} FUNCTION spiralOrder(matrix):
result ← empty list
IF length(matrix) = 0 OR length(matrix[0]) = 0:
RETURN result
top ← 0
bottom ← length(matrix) - 1
left ← 0
right ← length(matrix[0]) - 1
WHILE top ≤ bottom AND left ≤ right:
FOR col FROM left TO right:
append matrix[top][col] to result
top ← top + 1
FOR row FROM top TO bottom:
append matrix[row][right] to result
right ← right - 1
IF top ≤ bottom:
FOR col FROM right DOWNTO left:
append matrix[bottom][col] to result
bottom ← bottom - 1
IF left ≤ right:
FOR row FROM bottom DOWNTO top:
append matrix[row][left] to result
left ← left + 1
RETURN result