Spiral Matrix

MediumArrayMatrixSimulation

Solution

export function spiralOrder(matrix: number[][]): number[] {
  const [m, n] = [matrix.length, matrix[0].length];
 
  const result: number[] = [];
  let [sy, sx, ey, ex] = [0, 0, m - 1, n - 1];
 
  while (result.length < m * n) {
    for (let x = sx; x <= ex; x++) {
      result.push(matrix[sy][x]);
    }
 
    for (let y = sy + 1; y <= ey; y++) {
      result.push(matrix[y][ex]);
    }
 
    if (sy !== ey) {
      for (let x = ex - 1; x >= sx; x--) {
        result.push(matrix[ey][x]);
      }
    }
 
    if (sx !== ex) {
      for (let y = ey - 1; y > sy; y--) {
        result.push(matrix[y][sx]);
      }
    }
 
    sy += 1;
    sx += 1;
    ey -= 1;
    ex -= 1;
  }
 
  return result;
}
 
/* BFS */
// export function spiralOrder(matrix: number[][]): number[] {
//   const INVALID_VALUE = -100_000;
//   const [m, n] = [matrix.length, matrix[0].length];
//   const moves: Array<(y: number, x: number) => [number, number]> = [
//     (y, x) => [y, x + 1] /* Left */,
//     (y, x) => [y + 1, x] /* Down */,
//     (y, x) => [y, x - 1] /* Right */,
//     (y, x) => [y - 1, x] /* Up */,
//   ];
 
//   const result = [matrix[0][0]];
//   matrix[0][0] = INVALID_VALUE;
 
//   let [cy, cx, move] = [0, 0, 0];
//   while (result.length < m * n) {
//     const [ny, nx] = moves[move](cy, cx);
//     if (0 <= ny && ny < m && 0 <= nx && nx < n && matrix[ny][nx] !== INVALID_VALUE) {
//       matrix[ny][nx] = INVALID_VALUE;
//       result.push(matrix[ny][nx]);
//       [cy, cx] = [ny, nx];
//     } else {
//       move = (move + 1) % 4;
//     }
//   }
 
//   return result;
// }