Skip to content

Commit b06da43

Browse files
committed
spiral matrix solution
1 parent 4f67fcf commit b06da43

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

spiral-matrix/devyejin.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
6+
dr = (0, 1, 0, -1)
7+
dc = (1, 0, -1, 0)
8+
r, c, d = 0, 0, 0
9+
10+
n, m = len(matrix), len(matrix[0])
11+
12+
result = []
13+
VISITED = None
14+
for _ in range(n * m):
15+
result.append(matrix[r][c])
16+
matrix[r][c] = VISITED
17+
18+
nr, nc = r + dr[d], c + dc[d]
19+
20+
if 0 <= nr < n and 0 <= nc < m and matrix[nr][nc] != VISITED:
21+
r, c = nr, nc
22+
continue
23+
24+
d = (d + 1) % 4
25+
r += dr[d]
26+
c += dc[d]
27+
28+
return result

0 commit comments

Comments
 (0)