How to generate an n x n matrix filled with elements from 1 to N^2 in spiral order in JavaScript

1 Answer

0 votes
function generateSpiralMatrix(n) {
  const matrix = Array.from({ length: n }, () => Array(n).fill(0));
  let top = 0,
      bottom = n - 1,
      left = 0,
      right = n - 1;
  let num = 1;

  while (top <= bottom && left <= right) {
    // Fill top row
    for (let i = left; i <= right; i++) {
      matrix[top][i] = num++;
    }
    top++;

    // Fill right column
    for (let i = top; i <= bottom; i++) {
      matrix[i][right] = num++;
    }
    right--;

    // Fill bottom row
    if (top <= bottom) {
      for (let i = right; i >= left; i--) {
        matrix[bottom][i] = num++;
      }
      bottom--;
    }

    // Fill left column
    if (left <= right) {
      for (let i = bottom; i >= top; i--) {
        matrix[i][left] = num++;
      }
      left++;
    }
  }

  return matrix;
}

const n = 3;
const spiralMatrix = generateSpiralMatrix(n);

// Print the matrix
spiralMatrix.forEach(row => {
  console.log(row.join("\t"));
});



/*
run:

1	2	3
8	9	4
7	6	5

*/


 



answered Jun 25 by avibootz
...