forked from y-ncao/Python-Study
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSpiral_Matrix_II.py
53 lines (47 loc) · 1.37 KB
/
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
emw"""
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3,
You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
"""
class Solution:
# @return a list of lists of integer
def generateMatrix(self, n):
ret = [ [ 0 for i in range(n)] for j in range(n) ]
num = 1
start_row = start_col = 0
end_row = end_col = n - 1
while True:
for i in range(start_col, end_col + 1):
ret[start_row][i] = num
num += 1
start_row += 1
if start_row > end_row:
break
for i in range(start_row, end_row + 1):
ret[i][end_col] = num
num += 1
end_col -= 1
if start_col > end_col:
break
for i in range(end_col, start_col - 1, -1):
ret[end_row][i] = num
num += 1
end_row -= 1
if start_row > end_row:
break
for i in range(end_row, start_row -1, -1):
ret[i][start_col] = num
num += 1
start_col += 1
if start_col > end_col:
break
# This is the old way
#if n%2 == 1:
# ret[start_col][start_row] = num
return ret