返回
如何理解螺旋矩阵中的奥秘
后端
2024-01-19 03:25:27
一、螺旋矩阵
螺旋矩阵的题目要求如下:
给定一个二维数组matrix,其中包含m x n个整数,请你将该数组中的元素按螺旋顺序输出。
例如,对于以下二维数组:
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
输出应为:
[1, 2, 3, 6, 9, 8, 7, 4, 5]
实现方法:
- 定义四个指针top, bottom, left, right ,分别指向矩阵的顶部、底部、左边界和右边界。
- 定义一个空的列表result来存储输出结果 。
- 使用while循环,只要top <= bottom和left <= right,就一直循环 。
- 在循环中,将矩阵中从left到right列、从top到bottom行上的元素按顺序添加到result中 。
- 然后,将top加1,将bottom减1,将left加1,将right减1 ,缩小矩阵的范围。
- 重复步骤3和4,直到top > bottom或left > right 。
代码实现:
def spiral_matrix(matrix):
if not matrix:
return []
top, bottom = 0, len(matrix) - 1
left, right = 0, len(matrix[0]) - 1
result = []
while top <= bottom and left <= right:
for i in range(left, right + 1):
result.append(matrix[top][i])
for i in range(top + 1, bottom):
result.append(matrix[i][right])
if top < bottom:
for i in range(right, left - 1, -1):
result.append(matrix[bottom][i])
if left < right:
for i in range(bottom - 1, top, -1):
result.append(matrix[i][left])
top += 1
bottom -= 1
left += 1
right -= 1
return result
二、螺旋矩阵II
螺旋矩阵II的题目要求如下:
给定一个正整数n,生成一个n x n的螺旋矩阵,矩阵中的元素按螺旋顺序递增排列。
例如,对于n = 3,输出应为:
[[1, 2, 3],
[8, 9, 4],
[7, 6, 5]]
实现方法:
- 创建一个n x n的二维数组matrix,并将其所有元素初始化为0 。
- 定义变量row和col,分别指向当前行和当前列 。
- 定义变量count,表示当前要填充的元素值 。
- 使用while循环,只要count小于等于n 2,就一直循环。
- 在循环中,将matrix[row][col]设置为count,并将count加1 。
- 然后,根据当前的位置,更新row和col的值 。
- 重复步骤3和4,直到count大于n 2。
代码实现:
def spiral_matrix_ii(n):
matrix = [[0] * n for _ in range(n)]
row, col = 0, 0
count = 1
while count <= n ** 2:
matrix[row][col] = count
count += 1
if row == 0 or matrix[row - 1][col] != 0:
col += 1
else:
row -= 1
if col == n - 1 or matrix[row][col + 1] != 0:
row += 1
else:
col -= 1
if row == n - 1 or matrix[row + 1][col] != 0:
col -= 1
else:
row += 1
if col == 0 or matrix[row][col - 1] != 0:
row -= 1
else:
col += 1
return matrix