给你一个正整数 n ,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。
示例 1:
输入:n = 3
输出:[[1,2,3],[8,9,4],[7,6,5]]
示例 2:
输入:n = 1
输出:[[1]]
提示:
- 1 <= n <= 20
Python 解答:
class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
matrix = [[0 for i in range(n)] for j in range(n)]
i, j = 0, n-1
s = 1
while j > i:
for k in range(i, j):
matrix[i][k] = s
s += 1
for k in range(i, j):
matrix[k][j] = s
s += 1
for k in range(j, i, -1):
matrix[j][k] = s
s += 1
for k in range(j, i, -1):
matrix[k][i] = s
s += 1
i += 1
j -= 1
if i == j:
matrix[i][j] = s
return matrix
留言