59. 螺旋矩阵 II

class Solution:
    def generateMatrix(self, n):
        res = [[0] * n for _ in range(n)]
        loop, mid = n // 2, n // 2  # loop表示需要多少轮,mid用来填补当n为奇数时的最中间那个数,其实和loop的值一样,为了方便理解
        count = 1  # 计数
        start_x = 0

        for offset in range(1, loop + 1):  # offset是每一轮的偏移量
            
            for i_right in range(start_x, n - offset):  # 从左到右
                res[start_x][i_right] = count
                count += 1

            for i_down in range(start_x, n - offset):   # 从上往下
                res[i_down][n - offset] = count
                count += 1

            for i_left in range(n - offset, start_x, -1):  # 从右到左
                res[n - offset][i_left] = count
                count += 1

            for i_up in range(n - offset, start_x, -1):   # 从下到上
                res[i_up][start_x] = count
                count += 1

            start_x += 1

        if n % 2 != 0:  # n为奇数的话,将最中间那个数单独填充
            res[mid][mid] = count

        return res

你可能感兴趣的:(力扣,python,数据结构)