题目:给你一个正整数 n ,生成一个包含 1 到 n^2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。
链接 https://leetcode.cn/problems/spiral-matrix-ii/
class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
ans = [[0] * n for _ in range(n)]
# 左右上下的边界
l,r,t,b = 0,n-1,0,n-1
num = 1
while num <= n * n:
# 左到右
for i in range(l,r+1):
ans[t][i] = num
num += 1
t += 1
# 上到下
for i in range(t,b+1):
ans[i][r] = num
num += 1
r -= 1
# 右到左
for i in range(r,l-1,-1):
ans[b][i] = num
num += 1
b -= 1
# 下到上
for i in range(b,t-1,-1):
ans[i][l] = num
num += 1
l += 1
return ans
复杂度分析
时间复杂度:O(n^2),其中 n 是给定的正整数。矩阵的大小是 n×n,需要填入矩阵中的每个元素。
空间复杂度:O(1)。除了返回的矩阵以外,空间复杂度是常数。
class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
dirs = [(0, 1), (1, 0), (0, -1), (-1, 0)]
matrix = [[0] * n for _ in range(n)]
row, col, dirIdx = 0, 0, 0
for i in range(n * n):
matrix[row][col] = i + 1
dx, dy = dirs[dirIdx]
r, c = row + dx, col + dy
if r < 0 or r >= n or c < 0 or c >= n or matrix[r][c] > 0:
dirIdx = (dirIdx + 1) % 4 # 顺时针旋转至下一个方向
dx, dy = dirs[dirIdx]
row, col = row + dx, col + dy
return matrix
class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
matrix = [[0] * n for _ in range(n)]
num = 1
left, right, top, bottom = 0, n - 1, 0, n - 1
while left <= right and top <= bottom:
for col in range(left, right + 1):
matrix[top][col] = num
num += 1
for row in range(top + 1, bottom + 1):
matrix[row][right] = num
num += 1
if left < right and top < bottom:
for col in range(right - 1, left, -1):
matrix[bottom][col] = num
num += 1
for row in range(bottom, top, -1):
matrix[row][left] = num
num += 1
left += 1
right -= 1
top += 1
bottom -= 1
return matrix
参考:
作者:LeetCode-Solution
链接:https://leetcode.cn/problems/spiral-matrix-ii/solution/luo-xuan-ju-zhen-ii-by-leetcode-solution-f7fp/