Re: [闲聊] 每日leetcode

楼主: dont   2024-09-09 11:45:12
2326. Spiral Matrix IV
## 思路
先建default=-1的matrix
跑linked list
每次检查下一个(nr,nc) 能不能填, 不能填就换方向
## Code
```python
class Solution:
def spiralMatrix(self, m: int, n: int, head: Optional[ListNode]) ->
List[List[int]]:
res = [[-1] * n for _ in range(m)]
res[0][0] = head.val
head = head.next
r = c = i = 0
dirs = [(0, 1), (1, 0), (0, -1), (-1, 0)]
while head:
nr, nc = r + dirs[i][0], c + dirs[i][1]
if 0 <= nr < m and 0 <= nc < n and res[nr][nc] == -1:
res[nr][nc] = head.val
head = head.next
r, c = nr, nc
else:
i = (i+1) % 4
return res
```

Links booklink

Contact Us: admin [ a t ] ucptt.com