Skip to content

螺旋矩阵 II-59 #113

Open
Open
@sl1673495

Description

@sl1673495

给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。

示例:

输入: 3
输出:
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/spiral-matrix-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路

这题基本上就是和 螺旋矩阵-54 反过来了,54 题是把值按顺序输出出来,这题是按顺序重建二维数组,稍作改动即可完成。

/**
 * @param {number} n
 * @return {number[][]}
 */
let generateMatrix = function (n) {

    // 记录一个 visited 数组
    // 按照 右 -> 下 -> 左 -> 上 的方向不断前进
    // 直到遇到边界或者已经访问过的元素 则切换成下一个方向
    let dirs = [
        [0, 1], // 右
        [1, 0], // 下
        [0, -1], // 左
        [-1, 0], // 上
    ]

    let currentDirIndex = 0

    let visited = []
    for (let y = 0; y < n; y++) {
        visited[y] = []
    }
    let isValid = (y, x) => {
        return y >= 0 && y < n && x >= 0 && x < n && !visited[y][x]
    }

    let targetLength = n * n
    let res = []
    for (let y = 0; y < n; y++) {
        res[y] = []
    }

    let helper = (y, x, num) => {
        res[y][x] = num

        if (num === targetLength) {
            return res
        }

        visited[y][x] = true
        let [diffY, diffX] = dirs[currentDirIndex % 4]
        let nextY = y + diffY
        let nextX = x + diffX
        if (!isValid(nextY, nextX)) {
            [diffY, diffX] = dirs[++currentDirIndex % 4]
            nextY = y + diffY
            nextX = x + diffX
        }
        helper(nextY, nextX, num + 1)
    }

    helper(0, 0, 1)

    return res
};

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions