題目:
給定一個包含 m x n 個元素的矩陣(m 行, n 列),請按照順時針螺旋順序,返回矩陣中的所有元素。
思路:
使用兩個指針,然后控制好邊界就可以了。
程序:
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
row = len(matrix)
if row <= 0:
return []
column = len(matrix[0])
result = []
row_begin = 0
row_end = row - 1
column_begin = 0
column_end = column - 1
while row_begin <= row_end and column_begin <= column_end:
for index1 in range(column_begin, column_end + 1):
result.append(matrix[row_begin][index1])
row_begin += 1
for index2 in range(row_begin, row_end + 1):
result.append(matrix[index2][column_end])
column_end -= 1
for index1 in range(column_end, column_begin - 1, -1):
if row_end >= row_begin:
result.append(matrix[row_end][index1])
row_end -= 1
for index2 in range(row_end, row_begin - 1, -1):
if column_end >= column_begin:
result.append(matrix[index2][column_begin])
column_begin += 1
return result