Skip to content

Commit 0badc72

Browse files
59. Spiral Matrix II
1 parent dbdf3cc commit 0badc72

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed

Medium/59.SpiralMatrixII.py

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
"""
2+
Given a positive integer n, generate an n x n matrix filled with elements
3+
from 1 to n^2 in spiral order.
4+
5+
Example:
6+
Input: n = 3
7+
Output: [[1,2,3],[8,9,4],[7,6,5]]
8+
9+
Example:
10+
Input: n = 1
11+
Output: [[1]]
12+
13+
Constraints:
14+
- 1 <= n <= 20
15+
"""
16+
#Difficulty: Medium
17+
#20 / 20 test cases passed.
18+
#Runtime: 28 ms
19+
#Memory Usage: 14.4 MB
20+
21+
#Runtime: 28 ms, faster than 84.67% of Python3 online submissions for Spiral Matrix II.
22+
#Memory Usage: 14.4 MB, less than 26.01% of Python3 online submissions for Spiral Matrix II.
23+
24+
class Solution:
25+
def generateMatrix(self, n: int) -> List[List[int]]:
26+
row = 0
27+
col = 0
28+
val = 1
29+
matrix = [[None for i in range(n)] for j in range(n)]
30+
reverse = False
31+
while val <= n**2:
32+
if not reverse:
33+
while col < n:
34+
if matrix[row][col] is None:
35+
matrix[row][col] = val
36+
col += 1
37+
val += 1
38+
else:
39+
break
40+
col -= 1
41+
if matrix[row][col] is not None or col == n:
42+
row += 1
43+
while row < n:
44+
if matrix[row][col] is None:
45+
matrix[row][col] = val
46+
row += 1
47+
val += 1
48+
else:
49+
break
50+
row -= 1
51+
if matrix[row][col] is not None or row == n:
52+
col -= 1
53+
reverse = not reverse
54+
else:
55+
while col >= 0:
56+
if matrix[row][col] is None:
57+
matrix[row][col] = val
58+
col -= 1
59+
val += 1
60+
else:
61+
break
62+
if matrix[row][col] is not None or col < 0:
63+
col += 1
64+
row -= 1
65+
while row >= 0:
66+
if matrix[row][col] is None:
67+
matrix[row][col] = val
68+
row -= 1
69+
val += 1
70+
else:
71+
break
72+
if matrix[row][col] is not None or row < 0:
73+
col += 1
74+
row += 1
75+
reverse = not reverse
76+
return matrix

0 commit comments

Comments
 (0)