Skip to content

Spiral Matrix

spiralMatrix.js

js
const generateSpiralMatrix = (rows, cols) => {
  const matrix = Array(rows)
    .fill([])
    .map(() => Array(cols).fill(""));

  let rowStart = 0;
  let rowEnd = rows - 1;
  let columnStart = 0;
  let columnEnd = cols - 1;

  while (rowStart <= rowEnd && columnStart <= columnEnd) {
    for (let i = columnStart; i <= columnEnd; i++) {
      matrix[rowStart][i] = "→";
    }
    rowStart++;

    for (let i = rowStart; i <= rowEnd; i++) {
      matrix[i][columnEnd] = "↓";
    }
    columnEnd--;

    if (rowStart <= rowEnd) {
      for (let i = columnEnd; i >= columnStart; i--) {
        matrix[rowEnd][i] = "←";
      }
    }
    rowEnd--;

    if (columnStart <= columnEnd) {
      for (let i = rowEnd; i >= rowStart; i--) {
        matrix[i][columnStart] = "↑";
      }
    }
    columnStart++;
  }

  return matrix;
};

/*
[
  ["→", "→", "→", "→", "→"],
  ["↑", "→", "→", "→", "↓"],
  ["↑", "↑", "→", "↓", "↓"],
  ["↑", "←", "←", "↓", "↓"],
  ["←", "←", "←", "←", "↓"]
]
*/
const spiralMatrix = generateSpiralMatrix(5, 5);

Released under the MIT License.