今天是紀錄LeetCode解題的第五十四天
第五十四題題目:Given an m x n matrix, return all elements of the matrix in spiral order.
給定一個m * n的矩陣,按螺旋順序傳回所有元素
設定一個布林陣列儲存已走過的元素,以及定義derection儲存目前要存的下一個元素的方向,我們從題目可以得知要按螺旋順序遍歷元素方向為右 → 下 → 左 → 上不斷循環,每次遍歷只要判斷該次是否到達邊界,或此元素是否已經儲存過,沒有的話就繼續按照該方向儲存下一個元素,反之則改變方向
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
derection = "right"
ismove = [[False] * len(matrix[0]) for _ in range(len(matrix))]
row,col = 0,0
ismove[row][col] = True
result = [matrix[row][col]]
while not all(ismove[row][col] for row in range(len(matrix)) for col in range(len(matrix[0]))):
if derection == "right":
if col + 1 < len(matrix[row]) and not ismove[row][col+1]:
col += 1
ismove[row][col] = True
result.append(matrix[row][col])
else:
derection = "down"
elif derection == "down":
if row + 1 < len(matrix) and not ismove[row+1][col]:
row += 1
ismove[row][col] = True
result.append(matrix[row][col])
else:
derection = "left"
elif derection == "left":
if col - 1 >= 0 and not ismove[row][col-1]:
col -= 1
ismove[row][col] = True
result.append(matrix[row][col])
else:
derection = "up"
elif derection == "up":
if row - 1 >= 0 and not ismove[row-1][col]:
row -= 1
ismove[row][col] = True
result.append(matrix[row][col])
else:
derection = "right"
return result
這題的執行過程很單純,就是先向右(col + 1)依序儲存1、2、3,到達邊界了,所以改變方向成向下(row + 1)儲存6、9,又抵達邊界了,改變方向成向左(col - 1)儲存8、7,又遇到邊界,再改變方向成向上(row - 1)儲存4,接著往上檢查發現1已經被儲存過,所以再次改變方向成向右儲存最後一個數5,最後答案輸出為[1,2,3,6,9,8,7,4,5]