Skip to content

Commit 64d3e3c

Browse files
authored
Create Spiral_Matrix_II.py
1 parent 10ad1b5 commit 64d3e3c

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
class Solution:
2+
def generateMatrix(self, n: int) -> List[List[int]]:
3+
mat = [[0 for _ in range(n)] for _ in range(n)]
4+
key = 1
5+
top, down, right, left = 0, n, n, 0
6+
7+
# Directions - 0 -> left to right; 1 -> top to down;
8+
# 2 -> right to left; 3 -> down to top
9+
d = 0
10+
while left <= right and top <= down:
11+
if d == 0: # Move from Left to right
12+
for i in range(left, right):
13+
mat[top][i] = key
14+
key += 1
15+
top += 1
16+
d = 1
17+
elif d == 1: # Move from Top to Down
18+
for i in range(top, down):
19+
mat[i][right-1] = key
20+
key += 1
21+
right -= 1
22+
d = 2
23+
elif d == 2: # Move from right to left
24+
for i in range(right-1, left-1,-1):
25+
mat[down-1][i] = key
26+
key += 1
27+
down -= 1
28+
d = 3
29+
elif d == 3: # Move from down to top
30+
for i in range(down-1, top-1, -1):
31+
mat[i][left] = key
32+
key += 1
33+
left += 1
34+
d = 0
35+
36+
return mat
37+
38+

0 commit comments

Comments
 (0)