Spiral Matrix IV - Leetcode 2326 - Python

preview_player
Показать описание


0:00 - Read the problem
0:30 - Drawing Explanation
7:45 - Coding Explanation
13:17 - Coding Explanation 2

leetcode 2326

#neetcode #leetcode #python
Рекомендации по теме
Комментарии
Автор


Will also be making weekly system design videos, along with this weekly newsletter! Check it out and let me know what you think :)

NeetCodeIO
Автор

A more clear solution in my opinion.

class Solution:
def spiralMatrix(self, m: int, n: int, head: Optional[ListNode]) -> List[List[int]]:
res = [[-1] * n for x in range(m)]

current = head
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
d_idx = 0
i, j = 0, 0

while current:
res[i][j] = current.val
dy, dx = directions[d_idx]

# If the next move is out of bounds or if it tries to march into a pre-existing cell, change directions.
if i + dy < 0 or i + dy >= m or j + dx < 0 or j + dx >= n or res[i+dy][j+dx] > -1:
d_idx = (d_idx + 1) % len(directions)
dy, dx = directions[d_idx]

i += dy
j += dx

current = current.next

return res

soupa
Автор

I think after solving spiral matrix I, II, III this gets more easier, because they basically have the same pattern

BrandonGarciaCode
Автор

Just think it like this:
- Cells initially all -1.
- We move in this pattern (right -> down -> left -> up) * repeat.
- Set cell to current linked list node each move.
- Change direction only when you go out of bound or touch a cell not -1.
- Stop when linked list ends.

akialter
Автор

even with 4 duplicate code blocks, i think first solution looks much much cleaner

PegasusKr
Автор

0:15 Exactly! I was able to reach the solution just because I knew how I solved the walking robot simulation problem

RajdeepJadeja
Автор

Beautifully explained! Thank you for the daily videos. Really appreciate it

MP-nyep
Автор

After watching too many NeetCode videos, this question is so intuitive to me.😅

corrogist
Автор

Oh god how many sequels will this have

pratiksinha
Автор

3:11 You kind of know exactly what to do, you just don’t know how to do it in terms of code, in terms of variables and loops and things like that. Well that’s what I’m gonna show you now. ❤️‍🔥❤️‍🔥

Kaviarasu_NS