Skip to main content

Spiral Matrix II

Problem statement

Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order.

Example 1:

Input: n = 3Output: [[1,2,3],[8,9,4],[7,6,5]]

Example 2:

Input: n = 1Output: [[1]]

Constraints:

  • 1 <= n <= 20

My solution

/**
* @param {number} n
* @return {number[][]}
*/
var generateMatrix = function(n) {
let row = 0;
let col = 0;
let count = 1;
let rowRange = [0, n - 1];
let colRange = [0, n - 1];

let matrix = Array.from({
length: n
}, () => Array.from({
length: n
}, () => 0))

const toRight = () => {
while (col <= colRange[1]) {
matrix[row][col] = count++;
col++
}
col--;
colRange[1]--
row++;
}

const toBottom = () => {
while (row <= rowRange[1]) {
matrix[row][col] = count++;
row++
}
row--;
rowRange[0]++;
col--;
}

const toLeft = () => {
while(col >= colRange[0]) {
matrix[row][col] = count++;
col--
};
col++;
colRange[0]++;
row--;
}

const toTop = () => {
while(row >= rowRange[0]) {
matrix[row][col] = count++;
row--
}
row++
rowRange[1]--
col++
}


while (rowRange[0] <= rowRange[1] && colRange[0] <= colRange[1]) {
toRight();
toBottom();
toLeft();
toTop();
}

return matrix;
};