iT邦幫忙

0

解LeetCode的學習筆記Day59_Spiral Matrix II

  • 分享至 

  • xImage
  •  

今天是紀錄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

https://ithelp.ithome.com.tw/upload/images/20251119/201792348gTleNwUHm.png

解題思路

這題和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


圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言