Skip to content

Latest commit

 

History

History
54 lines (44 loc) · 1.44 KB

59.螺旋矩阵II.md

File metadata and controls

54 lines (44 loc) · 1.44 KB

59.螺旋矩阵II

https://leetcode-cn.com/problems/spiral-matrix/

难度:中等

题目:

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

示例:

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

示例 2: 输入:n = 1 输出:[[1]]

分析:

  1. 根据点阵,将数据完成顺时针遍历方法
  2. 根据遍历顺序,填入递增值即可

解题:

class Solution:
    def generateMatrix(self, n: int) -> List[List[int]]:
        def get_num():
            for i in range(1, n * n + 2):
                yield i

        get_num = get_num()
        ret = [[0] * n for i in range(n)]
        left = top = 0
        right = bottom = n
        while left <= right and top <= bottom:
            for i in range(left, right):
                ret[top][i] = get_num.__next__()
            top += 1
            for i in range(top, bottom):
                ret[i][right - 1] = get_num.__next__()
            right -= 1
            for i in range(right - 1, left - 1, -1):
                ret[bottom - 1][i] = get_num.__next__()
            bottom -= 1
            for i in range(bottom - 1, top - 1, -1):
                ret[i][left] = get_num.__next__()
            left += 1
        return ret

欢迎关注我的公众号: 清风Python

我的个人博客:https://qingfengpython.cn