topic
Given a positive integer n, to generate a 1 n2 contains all of the elements, and the element arranged spirally clockwise order square matrix.
Example:
输入: 3
输出:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
answer
Like search, the definition of an array of moving up and down about representation. The amount of code can cry Liaoning ...
z = [
[0, 1], # 右
[1, 0], # 下
[0, -1], # 左
[-1, 0] # 上
]
Code:
class Solution:
# Time: O(N),N为数值个数
def generateMatrix(self, n):
if n == 0:
return []
ans = [[-1]*n for _ in range(n)] # 初始化为-1
z = [
[0, 1], # 右
[1, 0], # 下
[0, -1], # 左
[-1, 0] # 上
]
x = y = 0
cur = 1
while -1 in ans[n//2]:
if ans[x][y] == -1:
ans[x][y] = cur
cur += 1
while x + z[0][0] < n and y + z[0][1] < n and ans[x+z[0][0]][y+z[0][1]] == -1: # 向右
x = x + z[0][0]
y = y + z[0][1]
ans[x][y] = cur
cur += 1
while x + z[1][0] < n and y + z[1][1] < n and ans[x+z[1][0]][y+z[1][1]] == -1: # 向下
x = x + z[1][0]
y = y + z[1][1]
ans[x][y] = cur
cur += 1
while x + z[2][0] < n and y + z[2][1] < n and y + z[2][1] >= 0 and ans[x+z[2][0]][y+z[2][1]] == -1: # 向左
x = x + z[2][0]
y = y + z[2][1]
ans[x][y] = cur
cur += 1
while x + z[3][0] < n and x + z[3][0] >= 0 and y + z[3][1] < n and ans[x+z[3][0]][y+z[3][1]] == -1: # 向上
x = x + z[3][0]
y = y + z[3][1]
ans[x][y] = cur
cur += 1
return ans
s = Solution()
ans = s.generateMatrix(3)
print(ans)
# [
# [ 1, 2, 3 ],
# [ 8, 9, 4 ],
# [ 7, 6, 5 ]
# ]