Leetcode 54 螺旋矩阵 (每日一题 20210729)
生活随笔
收集整理的這篇文章主要介紹了
Leetcode 54 螺旋矩阵 (每日一题 20210729)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
給你一個 m 行 n 列的矩陣?matrix ,請按照 順時針螺旋順序 ,返回矩陣中的所有元素。示例 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]鏈接:https://leetcode-cn.com/problems/spiral-matrixclass Solution:def spaitalOrder(self,maxtirx:List[List[int]]):->List[int]:if not matrix or not matrix[0]:return []m, n, x, y, res, current = len(matrix), len(matrix[0]), 0, 0, [], 0left, right, up, down = 0, position = [(0,1),(1,0),(0,-1),(-1,0)]while len(res) != m * n:res.append(matrix[x][y])if current == 0 and y == right:current += 1up += 1elif current == 1 and x == down:current += 1right -= 1elif current == 2 and y == left:current += 1down -= 1elif current == 3 and x == up:current += 1left += 1current %= 4x += position[current][0]y += position[current][1]return res
總結
以上是生活随笔為你收集整理的Leetcode 54 螺旋矩阵 (每日一题 20210729)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Leetcode 240.剑指 Offe
- 下一篇: Leetcode 234 回文链表 (每