精華區beta Marginalman 關於我們 聯絡資訊
885. Spiral Matrix III ## 思路 模擬題, 東南各1步 西北各2步 東南各3步...etc 如果當前的位置在rows, cols範圍內就加進res ## Complexity Time: O(Rows * Cols) Space: O(1) ## Code 1. dirs = [(0, 1), (1, 0), (0, -1), (-1, 0)] dx, dy = dirs[k] ```python class Solution: def spiralMatrixIII(self, rows: int, cols: int, rStart: int, cStart: int) -> List[List[int]]: dirs = [(0, 1), (1, 0), (0, -1), (-1, 0)] ans = [] count = rows * cols size = 1 while count: for k in range(4): for _ in range(size): if 0 <= rStart < rows and 0 <= cStart < cols: ans.append([rStart, cStart]) count -= 1 rStart += dirs[k][0] cStart += dirs[k][1] if k & 1: size += 1 if count == 0: break return ans ``` 2. dx, dy = dy, -dx ```python class Solution: def spiralMatrixIII(self, rows: int, cols: int, rStart: int, cStart: int) -> List[List[int]]: dx, dy = 0, 1 ans = [] count = rows * cols size = 1 while count: for _ in range(size): if 0 <= rStart < rows and 0 <= cStart < cols: ans.append([rStart, cStart]) count -= 1 rStart += dx cStart += dy dx, dy = dy, -dx if dx == 0: size += 1 return ans ``` -- http://i.imgur.com/OLvBn3b.jpg -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 185.213.82.160 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1723096365.A.865.html ※ 編輯: dont (185.213.82.160 臺灣), 08/08/2024 13:53:05
smart0eddie: space 你是排除輸出嗎 08/08 13:55
dont: ? 跟你的寫法一樣? 08/08 14:06