leetcode刷题-59螺旋矩阵2
题目
给定一个正整数 n,生成一个包含 1 到 n^2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。
思路
与螺旋矩阵题完全一致
实现
class Solution: def generateMatrix(self, n: int) -> List[List[int]]: result = [[0 for _ in range(n)]for _ in range(n)] idx = 1 left, right, top, bottom = 0, n - 1, 0, n - 1 while left <= right and top <= bottom: for column in range(left, right + 1): result[top][column] = idx idx += 1 for row in range(top + 1, bottom + 1): result[row][right] = idx idx += 1 if left < right and top < bottom: for column in range(right - 1, left, -1): result[bottom][column] = idx idx += 1 for row in range(bottom, top, -1): result[row][left] = idx idx += 1 left, right, top, bottom = left + 1, right - 1, top + 1, bottom - 1 return result