-
Notifications
You must be signed in to change notification settings - Fork 0
/
spiral_matrix_iii.py
38 lines (30 loc) · 1.25 KB
/
spiral_matrix_iii.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
from typing import List
class Solution:
def spiralMatrixIII(self, rows: int, cols: int, rStart: int, cStart: int) -> List[List[int]]:
curr = [rStart, cStart]
ans = [curr]
# Check if current position is in the grid
def in_grid(curr):
return 0 <= curr[0] < rows and 0 <= curr[1] < cols
# Keep track of the movement functions so that we can easily toggle between them
# The idx variable represents the current function we are using
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
idx = 0
# The distance in which we move increases after every 2 moves, hence we increment distance after 2 moves
distance = 1
moves = 0
# While we haven't explored the entire grid, we keep moving
while len(ans) != rows * cols:
direction = directions[idx]
for i in range(distance):
curr = [curr[0] + direction[0], curr[1] + direction[1]]
if in_grid(curr):
ans.append(curr)
idx = (idx + 1) % 4
if moves == 1:
moves = 0
distance += 1
else:
moves += 1
return ans
# print(Solution().spiralMatrixIII(5, 6, 1, 4))