Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

59. 螺旋矩阵 II #20

Open
webVueBlog opened this issue Aug 30, 2022 · 0 comments
Open

59. 螺旋矩阵 II #20

webVueBlog opened this issue Aug 30, 2022 · 0 comments

Comments

@webVueBlog
Copy link
Owner

59. 螺旋矩阵 II

Description

Difficulty: 中等

Related Topics: 数组, 矩阵, 模拟

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

示例 1:

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

示例 2:

输入:n = 1
输出:[[1]]

提示:

  • 1 <= n <= 20

Solution

Language: JavaScript

/**
 * @param {number} n
 * @return {number[][]}
 */
var generateMatrix = function(n) {
    let left = 0
    let right = n - 1
    let bottom = n - 1
    let top = 0
    const total = n * n

    const dep = []

    for (let i = 0; i < n; i++) {
        dep[i] = []
    }

    let count = 0

    while (count < total) {
        for (let i = left; i <= right; i++) dep[left][i] = ++count
        top++
        for (let i = top; i <= bottom; i++) dep[i][right] = ++count
        right--
        for (let i = right; i >= left; i--) dep[bottom][i] = ++count
        bottom--
        for (let i = bottom; i >= top; i--) dep[i][left] = ++count
        left++
    }

    return dep
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant