输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
示例 1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]
示例 2:
输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]
限制:
0 <= matrix.length <= 100
0 <= matrix[i].length <= 100
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
if matrix is None:
return []
elif( len(matrix) == 0):
return []
elif len(matrix[0]) == 0:
return []
# print(len(matrix))
# 左,右,上,下边界
l,r,u,d = 0,len(matrix[0]) - 1,0,len(matrix) - 1
save_list = []
while l <= r or u <= d:
if u <= d:
# 从左到右打印
self.left_to_right(l, r, u, d, save_list, matrix)
# 从左往右打印后触发的条件,上边界加1
u += 1
if l <= r:
# 从上往下打印
self.up_to_down(l, r, u, d, save_list, matrix)
# 从上往下打印触发的条件是,右边界减1
r -= 1
if u <= d:
# 从右往左打印
self.right_to_left(l, r, u, d, save_list, matrix)
# 从右往左打印触发的条件是,下边界减1
d -= 1
if l <= r:
# 从下往上打印
self.down_to_up(l, r, u, d, save_list, matrix)
# 从下往上打印触发的条件是,左边界加1
l += 1
return save_list
def left_to_right(self, l, r, u, d, save_list, matrix):
while ( l <= r):
save_list.append(matrix[u][l])
# print(1,save_list)
l += 1
def up_to_down(self, l, r, u, d, save_list, matrix):
while( u <= d):
save_list.append(matrix[u][r])
# print(2,save_list)
u += 1
def right_to_left(self, l, r, u, d, save_list, matrix):
while( l <= r ):
save_list.append(matrix[d][r])
# print(3,save_list)
r -= 1
def down_to_up(self, l , r, u, d, save_list, matrix):
while( u <= d):
save_list.append(matrix[d][l])
# print(4,save_list)
d -= 1