矩阵模拟问题合集(Leetcode题解-Python语言)
生活随笔
收集整理的這篇文章主要介紹了
矩阵模拟问题合集(Leetcode题解-Python语言)
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
54. 螺旋矩陣(劍指 Offer 29. 順時(shí)針打印矩陣)
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首先考慮到,元素前進(jìn)的方向只有四個(gè),對(duì)應(yīng)方向的 x 與 y 如何變化是確定的。所以用一個(gè)direction 數(shù)組保存四個(gè)方向 [(0, 1), (1, 0), (0, -1), (-1, 0)]。另外要注意防止跑出界,每次準(zhǔn)備跑出界時(shí)就轉(zhuǎn)向。對(duì)于已經(jīng)取過(guò)數(shù)的格子,把它置 ‘a(chǎn)’ 即可,下一格為 ‘a(chǎn)’ 就轉(zhuǎn)向。
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與上一題類(lèi)似,區(qū)別在于本題不是給定矩陣求遍歷序列,而是給定一個(gè)數(shù)字 n 然后返回一個(gè) 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 # 四個(gè)方向的邊界x, y, num, Dir = rStart, cStart, 1, 0 # (x, y)為當(dāng)前節(jié)點(diǎn),num為當(dāng)前查找的數(shù)字,Dir為當(dāng)前的方向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 # 調(diào)轉(zhuǎn)方向向下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本題可以看作是給定一個(gè)起始點(diǎn),其上下左右為邊界,然后開(kāi)始順時(shí)針遍歷,如果元素正好在矩陣中,那就符合條件,加入到遍歷序列 ans 中。如果遇到邊界就把邊界向外擴(kuò)展,然后順時(shí)針轉(zhuǎn)向,再遍歷下一個(gè),直到把矩陣所有元素都遍歷過(guò)為止。
總結(jié)
以上是生活随笔為你收集整理的矩阵模拟问题合集(Leetcode题解-Python语言)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: iQOO12系列燃途版今天开售 起步51
- 下一篇: 快速幂算法相关题目(Leetcode题解