矩阵为方阵时:
给你一个正整数 n
,生成一个包含 1
到 n2
所有元素,且元素按顺时针顺序螺旋排列的 n x n
正方形矩阵 matrix
。
示例 1:
输入:n = 3 输出:[[1,2,3],[8,9,4],[7,6,5]]
示例 2:
输入:n = 1 输出:[[1]]
class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
arr = [[0] * n for _ in range(n)] #创建一个n*n的数组
count = 1
startx, starty = 0, 0
offset = 1 #偏移量
loop = n//2 #循环圈数
mid = n//2 #中心位置
while loop > 0: #!!!关键点在于循环内每条边都采用左闭右开区间赋值
for i in range(starty, n-offset): #range()取值为左闭右开,最大值为右边界-1
arr[startx][i] = count
count += 1
for i in range(startx, n-offset):
arr[i][n-offset] = count
count += 1
for i in range(n-offset, startx, -1):
arr[n-offset][i] = count
count += 1
for i in range(n-offset, starty, -1):
arr[i][startx] = count
count += 1
startx += 1
starty += 1
offset += 1
loop -= 1
if n%2:
arr[mid][mid] = n*n
return arr
矩阵不为方阵时:给你一个 m
行 n
列的矩阵 matrix
,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
startx, starty = 0, 0
m = len(matrix)
n = len(matrix[0])
arr =[0] * m * n
loop = min(m,n)//2
t = 0
offset = 1
#if m == 1: return matrix[0]
#if n == 1:
# arr = [matrix[i][0] for i in range(0, m)]
# return arr
while loop > 0: #处理循环边框数据
for i in range(starty, n-offset):
arr[t] = matrix[starty][i]
t += 1
for i in range(startx, m-offset):
arr[t] = matrix[i][n-offset]
t += 1
for i in range(n-offset, starty, -1):
arr[t] = matrix[m-offset][i]
t += 1
for i in range(m-offset, startx, -1):
arr[t] = matrix[i][starty]
t += 1
startx += 1
starty += 1
offset += 1
loop -= 1
if t == m*n:
return arr
#循环结束,若框内有剩余数据,处理框内数据
a = min(m//2, n//2)
b = max(m//2, n//2)
if m < n:
for i in range(a, n-offset+1):
arr[t] = matrix[a][i]
t += 1
elif m > n:
for i in range(a, m-offset+1):
arr[t] = matrix[i][a]
t += 1
else:
if m%2 != 0:
arr[t] = matrix[a][a]
return arr