Last Commit: 2023-09-16 17:23:28

views:

Table of Content

59. Spiral Matrix II

source: https://leetcode.com/problems/spiral-matrix-ii/

Question

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

模拟方向

二维数组,逐个变换方向插入:

  • fill函数代表:在这个坐标的下一个点完成操作
/**
 * @param {number} n
 * @return {number[][]}
 */
var generateMatrix = function(n) {
    const total = n*n;
    const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]];
    const ret = Array(n).fill(null).map(() => Array(n).fill(null));
    const fill = (y, x, n, v) => {
        if (v > total) {
            return;
        }
        const [offsetY, offsetX] = directions[n % directions.length];
        x += offsetX;
        y += offsetY;
        let crr = ret[y]?.[x];
        while (crr === null) {
            ret[y][x] = v;
            v += 1;
            const nextY = y + offsetY;
            const nextX = x + offsetX;
            if (ret[nextY]?.[nextX] === null) {
                x = nextX;
                y = nextY;
            }
            crr = ret[y]?.[x];
        }
        fill(y, x, n + 1, v);
    };
    fill(0, -1, 0, 1);
    return ret;
};

End

变换方向有一个比较重要的操作,就是要在变方向前取消操作。