-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy path59.py
41 lines (41 loc) · 1.25 KB
/
59.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
39
40
41
class Solution(object):
def generateMatrix(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
ret = [[0 for i in range(n)] for j in range(n)]
v, start = 1, 0
while start * 2 < n:
col = row = start
# left -> right
while col < n - start:
ret[row][col] = v
col += 1
v += 1
# top -> bottom
if n - 2 * start > 1 and row < n - start:
row += 1
col -= 1
while row < n - start:
ret[row][col] = v
row += 1
v += 1
# right -> left
if n - 2 * start > 1 and n - 2 * start > 1 and col >= start:
col -= 1
row -= 1
while col >= start:
ret[row][col] = v
col -= 1
v += 1
# bottom -> top
if n - 2 * start > 1 and n - 2 * start > 1 and row > start:
row -= 1
col += 1
while row > start:
ret[row][col] = v
v += 1
row -= 1
start += 1
return ret