矩阵模拟问题合集(Leetcode题解-Python语言)
生活随笔
收集整理的這篇文章主要介紹了
矩阵模拟问题合集(Leetcode题解-Python语言)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
54. 螺旋矩陣(劍指 Offer 29. 順時針打印矩陣)
class Solution:def spiralOrder(self, matrix: List[List[int]]) -> List[int]:ans = []count = 0m, n = len(matrix), len(matrix[0])length = m * ndirections = [(0, 1), (1, 0), (0, -1), (-1, 0)]x = y = Dir = 0while count < length:ans.append(matrix[x][y])matrix[x][y] = 'a'dx, dy = directions[Dir]if x + dx >= m or y + dy >= n or x + dx < 0 or y + dy < 0 or matrix[x + dx][y + dy] == 'a':Dir = Dir + 1 if Dir < 3 else 0dx, dy = directions[Dir]x += dxy += dycount += 1return ans首先考慮到,元素前進的方向只有四個,對應方向的 x 與 y 如何變化是確定的。所以用一個direction 數組保存四個方向 [(0, 1), (1, 0), (0, -1), (-1, 0)]。另外要注意防止跑出界,每次準備跑出界時就轉向。對于已經取過數的格子,把它置 ‘a’ 即可,下一格為 ‘a’ 就轉向。
59. 螺旋矩陣 II
class Solution:def generateMatrix(self, n: int) -> List[List[int]]:matrix = [[0] * n for _ in range(n)]directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]x = y = Dir = 0for i in range(1, n**2 + 1):matrix[x][y] = idx, dy = directions[Dir]if x + dx >= n or y + dy >= n or x + dx < 0 or y + dy < 0 or matrix[x + dx][y + dy] != 0:Dir = Dir + 1 if Dir < 3 else 0dx, dy = directions[Dir]x += dxy += dyreturn matrix與上一題類似,區(qū)別在于本題不是給定矩陣求遍歷序列,而是給定一個數字 n 然后返回一個 n**2 大小的矩陣。
885. 螺旋矩陣 III
class Solution:def spiralMatrixIII(self, rows: int, cols: int, rStart: int, cStart: int) -> List[List[int]]:ans= []directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]Left, Right, Upper, Bottom = cStart - 1, cStart + 1, rStart - 1, rStart + 1 # 四個方向的邊界x, y, num, Dir = rStart, cStart, 1, 0 # (x, y)為當前節(jié)點,num為當前查找的數字,Dir為當前的方向while num <= rows * cols:if x >= 0 and x < rows and y >= 0 and y < cols: # (x, y)在矩陣中ans.append([x, y])num += 1if Dir == 0 and y == Right: # 向右到右邊界Dir += 1 # 調轉方向向下Right += 1 # 右邊界右移elif Dir == 1 and x == Bottom: # 向下到底邊界Dir += 1Bottom += 1 # 底邊界下移elif Dir == 2 and y == Left: # 向左到左邊界Dir += 1Left -= 1 # 左邊界左移elif Dir == 3 and x == Upper: # 向上到上邊界Dir = 0Upper -= 1 # 上邊界上移dx, dy = directions[Dir]x += dxy += dyreturn ans本題可以看作是給定一個起始點,其上下左右為邊界,然后開始順時針遍歷,如果元素正好在矩陣中,那就符合條件,加入到遍歷序列 ans 中。如果遇到邊界就把邊界向外擴展,然后順時針轉向,再遍歷下一個,直到把矩陣所有元素都遍歷過為止。
總結
以上是生活随笔為你收集整理的矩阵模拟问题合集(Leetcode题解-Python语言)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: iQOO12系列燃途版今天开售 起步51
- 下一篇: 快速幂算法相关题目(Leetcode题解