Categories
interview

Spiral Matrix

/**
 * @param {number[][]} matrix
 * @return {number[]}
 */
const spiralOrder = function(matrix) {
  const list = [];
  let r1 = 0;
  let r2 = matrix.length - 1;
  let c1 = 0;
  let c2 = matrix[0].length - 1;
  while (c1 <= c2 && r1 <= r2) {
    for (let c = c1; c <= c2; c++)
      list.push(matrix[r1][c]);
    for (let r = r1 + 1; r <= r2; r++)
      list.push(matrix[r][c2]);
    if (r1 < r2 && c1 < c2) {
      for (let c = c2 - 1; c >= c1; c--)
        list.push(matrix[r2][c]);
      for (let r = r2 - 1; r > r1; r--)
        list.push(matrix[r][c1]);
    }
    r1++;
    r2--;
    c1++;
    c2--;
  }
  return list;
};

Output

const arr = [
  [1, 2, 3],
  [8, 9, 4],
  [7, 6, 5]
];

console.log(spiralOrder(arr));

// [1, 2, 3, 4, 5, 6, 7, 8, 9]

Demo