59. Spiral Matrix II

Problem


Tags: Array, Matrix, Simulation

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

Example 1:

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

Example 2:

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

Constraints:

  • 1 <= n <= 20

Code

JS

// 59. Spiral Matrix II (4/17/53841)
// Runtime: 76 ms (19.46%) Memory: 38.85 MB (94.69%) 

/**
 * @param {number} n
 * @return {number[][]}
 */
function generateMatrix(n) {
    const matrix = Array.from({ length: n }).map(() => Array.from({ length: n }));
    
    let x = 0, y = 0, direction = 0, level = 0;
    for(let i = 1; i <= n*n; i++) {
        matrix[y][x] = i;
        
        if(direction === 0 && x >= n - level - 1) direction = 1;
        else if(direction === 1 && y >= n - level - 1) direction = 2;
        else if(direction === 2 && x <= level) direction = 3;
        else if(direction === 3 && y <= level + 1) {
            level++;
            direction = 0;
        }
        
        if(direction === 0) x++;
        else if(direction === 1) y++;
        else if(direction === 2) x--;
        else if(direction === 3) y--;
    }
    
    return matrix;
};