题目:
给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
解答:
方法一:
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
m=len(matrix)
n=len(matrix[0])
res=[]
count = (min(m, n)+1) // 2 # 总共有多少层
res = [] # 保存结果
for lr in range(count):
start = lr # 该层左上角的位置(start, start)
last_col = n-1-lr # 该层最后一列的索引
last_row = m-1-lr # 该层最后一行的索引
for c in range(start, last_col+1): # from left to right
res.append(matrix[start][c])
for r in range(start+1,last_row+1): # from top to bottom
res.append(matrix[r][last_col])
if last_row != start and last_col != start:
for c1 in range(last_col-1, start-1, -1): # from right to bottom
res.append(matrix[last_row][c1])
for r1 in range(last_row-1, start, -1): # from bottom to top
res.append(matrix[r1][start])
return res
方法二:
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
m=len(matrix)
n=len(matrix[0])
count=min(m,n)//2
res=[]
i=-1
for i in range(count):
#从左到右
for j in range(i,n-1-i):
res.append(matrix[i][j])
j+=1
#从上到下
for k in range(i,m-1-i):
res.append(matrix[k][j])
k+=1
#从右到左
for j in range(n-1-i,i,-1):
res.append(matrix[k][j])
j-=1
#从下到上
for k in range(m-1-i,i,-1):
res.append(matrix[k][j])
#最内圈还有一个元素
if m==n and n%2==1:
res.append(matrix[i+1][i+1])
#最内圈还有一列
elif m>n and n%2==1:
for k in range(i+1,m-i-1):
res.append(matrix[k][i+1])
#最内圈还有一行
elif n>m and m%2==1:
for j in range(i+1,n-i-1):
res.append(matrix[i+1][j])
return res