-
Notifications
You must be signed in to change notification settings - Fork 0
/
059-SpiralMatrix2.py
34 lines (33 loc) · 951 Bytes
/
059-SpiralMatrix2.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
# Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
if n == 1: return [[1]]
result = [[0 for _ in range(n)] for _ in range(n)]
num = 1
i = j = 0
for z in range(n - 1):
while j < n - z:
result[i][j] = num
num += 1
j += 1
j -= 1
i += 1
while i < n - z:
result[i][j] = num
num += 1
i += 1
i -= 1
j -= 1
while j >= z:
result[i][j] = num
num += 1
j -= 1
j += 1
i -= 1
while i > z:
result[i][j] = num
num += 1
i -= 1
i += 1
j += 1
return result