Skip to content

Files

Latest commit

 

History

History
38 lines (35 loc) · 1.08 KB

0059. Spiral Matrix II.md

File metadata and controls

38 lines (35 loc) · 1.08 KB

Screen Shot 2022-10-13 at 11 50 59 PM

/**
 * @param {number} n
 * @return {number[][]}
 */
var generateMatrix = function(n) {
    let grid = new Array(n).fill().map(() => new Array(n).fill(-1));
    let startRow = 0, endRow = n - 1, startCol = 0, endCol = n - 1;
    let value = 1;
    
    while(startRow <= endRow && startCol <= endCol) {
        for(let col = startCol; col <= endCol; col++) {
            grid[startRow][col] = value;
            value++;
        }
        for(let row = startRow + 1; row <= endRow; row++) {
            grid[row][endCol] = value;
            value++;
        }
        for(let col = endCol - 1; col >= startCol; col--) {
            grid[endRow][col] = value;
            value++;
        }
        for(let row = endRow - 1; row > startRow; row--) {
            grid[row][startCol] = value;
            value++;
        }
        startRow++;
        endRow--;
        startCol++;
        endCol--;
    }
    return grid
};