File tree 1 file changed +115
-0
lines changed
1 file changed +115
-0
lines changed Original file line number Diff line number Diff line change
1
+ """
2
+ Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
3
+
4
+ Example:
5
+
6
+ Input: 3
7
+ Output:
8
+ [
9
+ [ 1, 2, 3 ],
10
+ [ 8, 9, 4 ],
11
+ [ 7, 6, 5 ]
12
+ ]
13
+
14
+
15
+ 想清楚在写。
16
+
17
+ beat 94%
18
+
19
+ 测试地址:
20
+ https://leetcode.com/problems/spiral-matrix-ii/description/
21
+
22
+ """
23
+ class Solution (object ):
24
+
25
+ def generateMatrix (self , n ):
26
+ """
27
+ :type n: int
28
+ :rtype: List[List[int]]
29
+ """
30
+
31
+ maps = [[0 for i in range (n )] for j in range (n )]
32
+
33
+ current_value = [i for i in range (1 , n * n + 1 )]
34
+ current_value .reverse ()
35
+
36
+ def makeXY (x , y ):
37
+ # up
38
+ # down
39
+ # right
40
+ # left
41
+ return [(x , y - 1 ),
42
+ (x , y + 1 ),
43
+ (x + 1 , y ),
44
+ (x - 1 , y )]
45
+
46
+ def right (x , y ):
47
+
48
+ while 1 :
49
+ if not current_value :
50
+ return maps
51
+ xy = makeXY (x , y )
52
+ if (y > - 1 and x > - 1 ) and (y < n and x < n ):
53
+ if maps [y ][x ] == 0 :
54
+ maps [y ][x ] = current_value .pop ()
55
+ y , x = xy [2 ][1 ], xy [2 ][0 ]
56
+ else :
57
+ # down
58
+ return down (x - 1 , y + 1 )
59
+ else :
60
+ # down
61
+ return down (x - 1 , y + 1 )
62
+
63
+ def down (x , y ):
64
+
65
+ while 1 :
66
+ if not current_value :
67
+ return maps
68
+ xy = makeXY (x , y )
69
+ if (y > - 1 and x > - 1 ) and (y < n and x < n ):
70
+ if maps [y ][x ] == 0 :
71
+ maps [y ][x ] = current_value .pop ()
72
+ y , x = xy [1 ][1 ], xy [1 ][0 ]
73
+
74
+ else :
75
+ # left
76
+ return left (x - 1 , y - 1 )
77
+ else :
78
+ # left
79
+ return left (x - 1 , y - 1 )
80
+ def left (x , y ):
81
+
82
+ while 1 :
83
+ if not current_value :
84
+ return maps
85
+ xy = makeXY (x , y )
86
+
87
+ if y > - 1 and x > - 1 and y < n and x < n :
88
+ if maps [y ][x ] == 0 :
89
+ maps [y ][x ] = current_value .pop ()
90
+ y , x = xy [3 ][1 ], xy [3 ][0 ]
91
+ else :
92
+ # up
93
+ return up (x + 1 , y - 1 )
94
+ else :
95
+ # up
96
+ return up (x + 1 , y - 1 )
97
+ def up (x , y ):
98
+
99
+ while 1 :
100
+ if not current_value :
101
+ return maps
102
+ xy = makeXY (x , y )
103
+
104
+ if y > - 1 and x > - 1 and y < n and x < n :
105
+ if maps [y ][x ] == 0 :
106
+ maps [y ][x ] = current_value .pop ()
107
+ y , x = xy [0 ][1 ], xy [0 ][0 ]
108
+ else :
109
+ # right
110
+ return right (x + 1 , y + 1 )
111
+ else :
112
+ # right
113
+ return right (x + 1 , y + 1 )
114
+
115
+ return right (0 , 0 )
You can’t perform that action at this time.
0 commit comments