-
Notifications
You must be signed in to change notification settings - Fork 264
/
058 Spiral Matrix II.py
95 lines (78 loc) · 2.3 KB
/
058 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
"""
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 ]
]
"""
__author__ = 'Danyang'
class Solution:
def generateMatrix(self, n):
"""
algorithm: array, simulation
:param n: Integer
:return: a list of lists of integer
"""
left = 0
right = n - 1 # [0, n)
top = 0
bottom = n - 1 # [0, n)
result = [[-1 for _ in xrange(n)] for _ in xrange(n)]
num = 1
while left <= right and top <= bottom:
for i in xrange(left, right + 1): # tuning ending condition, be greedy
result[top][i] = num
num += 1
for i in xrange(top + 1, bottom):
result[i][right] = num
num += 1
for i in xrange(right, left, -1):
result[bottom][i] = num
num += 1
for i in xrange(bottom, top, -1):
result[i][left] = num
num += 1
left += 1
right -= 1
top += 1
bottom -= 1
return result
class SolutionError:
def generateMatrix(self, n):
"""
algorithm: array, simulation
:param n: Integer
:return: a list of lists of integer
"""
left = 0
right = n - 1 # [0, n)
top = 0
bottom = n - 1 # [0, n)
result = [[-1 for _ in xrange(n)] for _ in xrange(n)]
num = 1
while left <= right and top <= bottom:
for i in xrange(left, right): # tuning ending condition, this will fail in the middle
result[top][i] = num
num += 1
for i in xrange(top, bottom):
result[i][right] = num
num += 1
for i in xrange(right, left, -1):
result[bottom][i] = num
num += 1
for i in xrange(bottom, top, -1):
result[i][left] = num
num += 1
left += 1
right -= 1
top += 1
bottom -= 1
return result
if __name__=="__main__":
result = Solution().generateMatrix(4)
for row in result:
print row