原题链接
模拟顺时针画矩阵过程
class Solution(object):
def generateMatrix(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
res= [[0 for _ in range(n)] for _ in range(n)]#构建二维数组矩阵
mid=n//2#python中//除法结果取整
loop=n//2
startx=0
starty=0
offset=1
count=1
while(loop):
i=startx
j=starty
while(j<starty+n-offset):#循环过程保持左闭右开的原则
res[i][j]=count
count+=1
j=j+1
while(i<starty+n-offset):
res[i][j]=count
count+=1
i+=1
while(j>starty):
res[i][j]=count
count+=1
j=j-1
while(i>startx):
res[i][j]=count
count+=1
i=i-1
loop-=1
offset+=2
startx+=1
starty+=1
if(n%2):#n为奇数时考虑中间值
res[mid][mid]=count
return res
test=Solution()
print(test.generateMatrix(4))