Spiral Matrix Medium 0 attempts
LeetCode ↗

Spiral Matrix

Medium MatrixBFSDFS LeetCode

Given an m×n matrix, return all elements in spiral order.

Example: matrix = [[1,2,3],[4,5,6],[7,8,9]] → [1,2,3,6,9,8,7,4,5]

Sample Input
—
Sample Output
—
Constraints
  • 1 <= m, n <= 10
  • -100 <= matrix[i][j] <= 100
Topics

Boundary Shrinking

function spiralOrder(matrix) {
  const res = [];
  let top=0, bot=matrix.length-1, left=0, right=matrix[0].length-1;
  while (top<=bot && left<=right) {
    for (let i=left;i<=right;i++) res.push(matrix[top][i]); top++;
    for (let i=top;i<=bot;i++) res.push(matrix[i][right]); right--;
    if (top<=bot) { for (let i=right;i>=left;i--) res.push(matrix[bot][i]); bot--; }
    if (left<=right) { for (let i=bot;i>=top;i--) res.push(matrix[i][left]); left++; }
  }
  return res;
}

Time: O(mn) | Space: O(1)

Saved in this browser only. Private to you.

JavaScript