-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0059-spiral-matrix-ii.py
More file actions
34 lines (29 loc) · 770 Bytes
/
0059-spiral-matrix-ii.py
File metadata and controls
34 lines (29 loc) · 770 Bytes
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
# time complexity: O(m*n)
# space complexity: O(m*n)
from typing import List
class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
grid = [[0 for _ in range(n)] for _ in range(n)]
ROW = n
COL = n
direction = 1
row = 0
col = -1
i = 1
while ROW > 0 and COL > 0:
for _ in range(COL):
col += direction
grid[row][col] = i
i += 1
ROW -= 1
for _ in range(ROW):
row += direction
grid[row][col] = i
i += 1
COL -= 1
direction *= -1
return grid
n = 3
print(Solution().generateMatrix(3))
n = 1
print(Solution().generateMatrix(1))