23 Jan 59. Spiral Matrix II
Given a positive integer n
, generate an n x n
matrix
filled with elements from 1
to n2
in spiral order.
Example 1:
Input: n = 3 Output: [[1,2,3],[8,9,4],[7,6,5]]
Example 2:
Input: n = 1 Output: [[1]]
Constraints:
1 <= n <= 20
解题思路
根据方向和下一个填充的位置的对应,找到下一个位置,如果这个位置出边界或已经被填过,则转换方向
代码
class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
res = [[0] * n for _ in range(n)]
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
curx = cury = curd = 0
for i in range(1, n * n + 1):
res[curx][cury] = i
newx, newy = curx + directions[curd][0], cury + directions[curd][1]
if newx < 0 or newx >= n or newy < 0 or newy >= n or res[newx][newy]:
curd = (curd + 1) % 4
curx += directions[curd][0]
cury += directions[curd][1]
return res
https://maxming0.github.io/2020/12/07/Spiral-Matrix-II/
class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
matrix = []
num = 1
matrix=[[0 for _ in range(n)] for _ in range(n)]
print(matrix)
left, right, up, down = 0, n-1, 0, n-1
results = []
x, y = 0, 0
cur_d = 0
dirs = [(0,1),(1,0),(0,-1),(-1,0)]
count = n * n + 1
i = 1
while i < count:
matrix[x][y] = i
print(“—————-“)
print(x)
print(y)
newx = x + dirs[cur_d][0]
newy = y + dirs[cur_d][1]
print(newx)
print(newy)
if newx <0 or newx >=n or newy < 0 or newy >= n or matrix[newx][newy]:
cur_d = (cur_d + 1) % 4
x += dirs[cur_d][0]
y += dirs[cur_d][1]
i += 1
return matrix
No Comments