【Leetcode 数组】 螺旋矩阵 II(59)
题目
给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。
示例:
输入: 3
输出:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
解答
像搜索一样,定义一个表示上下左右移动的数组。可代码量,哭辽...
z = [
[0, 1], # 右
[1, 0], # 下
[0, -1], # 左
[-1, 0] # 上
]
代码实现:
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 ]
# ]