harrytothemoon / leetcodeAplus

Leetcode meeting note
2 stars 0 forks source link

[59] Spiral Matrix II #61

Open tsungtingdu opened 3 years ago

tsungtingdu commented 3 years ago
var generateMatrix = function(n) {
    let ans = new Array(n).fill().map(i => new Array(n).fill(null))
    let direction = [[0,1], [1, 0], [0, -1], [-1, 0]]
    let x = 0
    let y = 0

    ans[x][y] = 1
    let num = 2

    while(num <= n*n) {
        x += direction[0][0]
        y += direction[0][1]

        if (ans[x] === undefined || ans[x][y] === undefined || ans[x][y]) {
            x -= direction[0][0]
            y -= direction[0][1]
            direction.push(direction.shift())
        } else if (ans[x][y] === null) {
            ans[x][y] = num++
        }
    }
    return ans
};