Leetcode59-螺旋矩阵 II
思路:初始化一个二维数组。
二维数组的初始化方法: matrix = [[0] * n for _ in range(n)]
和螺旋数组一样的思路
代码:
def generateMatrix(n):
matrix = [[0] * n for _ in range(n)]
left, right = 0, n - 1
top, botton = 0, n - 1
elements = []
index = 0
for i in range(1, n * n + 1):
elements.append(i)
while True:
for i in range(left, right + 1):
matrix[top][i] = elements[index]
index += 1
top += 1
if top > botton:
break
for i in range(top, botton + 1):
matrix[i][right] = elements[index]
index += 1
right -= 1
if left > right:
break
for i in range(right, left - 1, -1):
matrix[botton][i] = elements[index]
index += 1
botton -= 1
if top > botton:
break
for i in range(botton, top - 1, -1):
matrix[i][left] = elements[index]
index += 1
left += 1
if left > right:
break
return matrix