DEV Community

Cover image for Spiral iteration algorithm
Davyd NRB
Davyd NRB

Posted on • Edited on

Spiral iteration algorithm

Solution for complex js interview questions

const directions = {
  x: [1, 0, -1, 0],
  y: [0, 1, 0, -1],
};

function spiral(matrix) {
  const rowCount = matrix.length;
  const colCount = matrix[0].length;
  const size = rowCount * colCount;
  const visited = new Array(rowCount).fill(0).map(() => new Array());
  const result = [];

  let x = y = direction = 0;

  for (let i = 0; i < size; i++) {
    result.push(matrix[y][x]);
    visited[y][x] = true;

    const diffX = x + directions.x[direction];
    const diffY = y + directions.y[direction];

    if (
      diffX >= 0 &&
      diffX < colCount &&
      diffY >= 0 &&
      diffY < rowCount &&
      !visited[diffY][diffX]
    ) {
      x = diffX;
      y = diffY;
    } else {
      direction = (direction + 1) % 4;

      x += directions.x[direction];
      y += directions.y[direction];
    }
  }

  return result;
}

spiral([
  [0,   1,  2,  3,  4],
  [5,   6,  7,  8,  9],
  [10, 11, 12, 13, 14],
  [15, 16, 17, 18, 19],
]); 

// [0, 1, 2, 3, 4, 9, 14, 19, 18, 17, 16, 15, 10, 5, 6, 7, 8, 13, 12, 11]

Enter fullscreen mode Exit fullscreen mode

Top comments (0)