class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
if matrix == []:
return matrix
#空矩阵返回空矩阵
T = 0
D = len(matrix) - 1
L = 0
R = len(matrix[0]) - 1
dir = 0
#0:? 1:? 2:? 3:?
m = len(matrix[0]) - 1
n = len(matrix) - 1
result = []
while T <= D and L <= R:
if dir == 0:
for i in range(L,R+1):
result.append(matrix[T][i])
T = T + 1
dir = 1
elif dir == 1:
for i in range(T,D+1):
result.append(matrix[i][R])
R = R - 1
dir = 2
elif dir == 2:
for i in range(R,L-1,-1):
result.append(matrix[D][i])
D = D - 1
dir = 3
elif dir == 3:
for i in range(D,T-1,-1):
result.append(matrix[i][L])
L = L + 1
dir = 0
return result
用T,D,L,R四个变量记录应该append进result的位置
还有一种方法就是
matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]
def spiralOrder(matrix):
if not matrix :
return []
res = []
while matrix:
res.extend(matrix.pop(0))
print("res = ",res)
next_matrix = []
#print(matrix)
for x in zip(*matrix):
print("x",x)
next_matrix.append(x)
print("next = ",next_matrix)
#print(next_matrix)
matrix = next_matrix[::-1]
print("matrix = ",matrix)
return res
spiralOrder(matrix)