Re: [閒聊] 每日leetcode

作者: dont   2024-08-08 13:52:43
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
```
作者: smart0eddie (smart0eddie)   2024-08-08 13:55:00
space 你是排除輸出嗎
作者: dont   2024-08-08 14:06:00
? 跟你的寫法一樣?

Links booklink

Contact Us: admin [ a t ] ucptt.com