-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSpiral Matrix II.py
36 lines (28 loc) · 933 Bytes
/
Spiral Matrix II.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
def generateMatrix(n: int):
ans = [[0 for i in range(n)] for j in range(n)]
row_start, col_start = 0, 0
row_end, col_end = len(ans) - 1, len(ans[0]) - 1
count = 1
while row_start <= row_end and col_start <= col_end:
for i in range(col_start, col_end + 1):
ans[row_start][i] = count
count += 1
row_start += 1
for i in range(row_start, row_end + 1):
ans[i][col_end] = count
count += 1
col_end -= 1
if row_start <= row_end:
for i in range(col_end, col_start - 1, -1):
ans[row_end][i] = count
count += 1
row_end -= 1
if col_start <= col_end:
for i in range(row_end, row_start - 1, -1):
ans[i][col_start] = count
count += 1
col_start += 1
for row in ans:
print(row)
n = 4
generateMatrix(n)