• LeetCode 59. 螺旋矩阵 II


    59. 螺旋矩阵 II

    Difficulty: 中等

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

    示例 1:

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

    示例 2:

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

    提示:

    • 1 <= n <= 20

    Solution

    跟54题属于同一道题,只不过此题不需要考虑特殊的矩阵形态。

    class Solution:
        def generateMatrix(self, n: int) -> List[List[int]]:
            res = [[0] * n for _ in range(n)]
            left, top, right, down = 0, 0, n - 1, n - 1
            cnt = 1
            while left <= right and top <= down:
                for i in range(left, right + 1):
                    res[top][i] = cnt
                    cnt += 1
                for i in range(top + 1, down + 1):
                    res[i][right] = cnt
                    cnt += 1
                for i in range(right - 1, left, -1):
                    res[down][i] = cnt
                    cnt += 1
                for i in range(down, top, -1):
                    res[i][left] = cnt
                    cnt +=1
                left += 1
                top += 1
                right -= 1
                down -= 1
            return res
    
  • 相关阅读:
    (考研)散列表和hashcode和hashmap
    java基本数据类型和引用类型
    Java 中的语法糖(7/15整个周六上午总结)
    数据库第一天-数据库索引
    MonoBehaviour生命周期
    Unity基础知识
    SQLite3笔记
    cocos_js写文件
    UGUI_屏幕适配
    KMS算法
  • 原文地址:https://www.cnblogs.com/swordspoet/p/14546455.html
Copyright © 2020-2023  润新知