0
点赞
收藏
分享

微信扫一扫

leetcode-59. 螺旋矩阵 II-js

向上的萝卜白菜 2022-03-10 阅读 38

题目

在这里插入图片描述

代码

var generateMatrix = function(n) {
    let matrix = []
    for (let i = 0; i < n; i++) {
        let arr = new Array(n).fill(0)
        matrix.push(arr)
    }
    let num = 1

    let upper_bound = 0, right_bound = n-1;
    let lower_bound = n-1, left_bound = 0;

    while(num <= n*n) {
        // 从左到右
        if(upper_bound <= lower_bound) {
            for (let i = left_bound; i <= right_bound; i++) {
                matrix[upper_bound][i] = num++
            }
            upper_bound++
        }

        // 从上到下
        if(right_bound >= left_bound) {
            for (let i = upper_bound; i <= lower_bound; i++) {
                matrix[i][right_bound] = num++
            }
            right_bound--
        }

        // 从右到左
        if(lower_bound >= upper_bound) {
            for (let i = right_bound; i >= left_bound; i--) {
                matrix[lower_bound][i] = num++
            }
            lower_bound--
        }

        // 从下到上
        if(left_bound <= right_bound) {
            for (let i = lower_bound; i >= upper_bound; i--) {
                matrix[i][left_bound] = num++
            }
            left_bound++
        }
    }

    return matrix
};

参考资料

  • 二维数组的花式遍历技巧
举报

相关推荐

0 条评论