写一下思路
先生成一个n*n的全零矩阵,主要判断在填充时候需要拐弯的边界条件:
- 数组越界
- 下一个填充的位置不为0
设置一个标识target,当其为0,表示向右填充。顺时针方向依次表示不同方向。
最后贴一下代码
class Solution(object):
def generateMatrix(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
mat = [[0] * n for _ in range(n)] # 生成全零矩阵
x, y = 0, 0
n2 = pow(n, 2)
target = 0
mat[x][y] = 1
for i in range(n2 - 1):
# 确定下次x y 的位置
if target == 0:
y += 1
if y == n or mat[x][y] != 0:
target = 1
y -= 1
x += 1
mat[x][y] = i + 2
continue
if target == 1:
x += 1
if x == n or mat[x][y] != 0:
target = 2
x -= 1
y -= 1
mat[x][y] = i + 2
continue
if target == 2:
y -= 1
if y == -1 or mat[x][y] != 0:
target = 3
y += 1
x -= 1
mat[x][y] = i + 2
continue
if target == 3:
x -= 1
if x == -1 or mat[x][y] != 0:
target = 0
x += 1
y += 1
mat[x][y] = i + 2
continue
mat[x][y] = i + 2
return mat
就是内存占用有点高