今天是紀錄LeetCode解題的第五十九天
第五十九題題目:Given a positive integer n, generate an n x n matrix filled with elements from 1 to n^2 in spiral order.
給定一個正整數n,產生一個以螺旋排序的n * n陣列,排序的元素從1 ~ n^2

這題和54題大同小異,定義derection = right、down、left、up,當目前的row、col沒有到邊界且該格沒有走過,則設置result[row][col] = num,否則把derection的方向改成下一個狀態
class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
derection = "right"
ismove = [[False] * n for _ in range(n)]
result = [[0] * n for _ in range(n)]
r,c = 0,0
ismove[r][c] = True
result[r][c] = 1
num = 2
while num <= n*n:
if derection == "right":
if c + 1 < n and not ismove[r][c+1]:
c += 1
ismove[r][c] = True
result[r][c] = num
num += 1
else:
derection = "down"
elif derection == "down":
if r + 1 < n and not ismove[r+1][c]:
r += 1
ismove[r][c] = True
result[r][c] = num
num += 1
else:
derection = "left"
elif derection == "left":
if c - 1 >= 0 and not ismove[r][c-1]:
c -= 1
ismove[r][c] = True
result[r][c] = num
num += 1
else:
derection = "up"
elif derection == "up":
if r - 1 >= 0 and not ismove[r-1][l]:
r -= 1
ismove[r][c] = True
result[r][c] = num
num += 1
else:
derection = "right"
return result
執行的過程和54題可以說是差不多,只是變成在遍歷時,把result填入數字1 ~ n^2