Python实现N阶方阵顺时针旋转M次算法
Python实现N阶方阵顺时针旋转M次算法
本文介绍如何使用Python实现一个算法,该算法能够将一个N阶方阵顺时针旋转M次。
代码实现
def rotateMatrix(matrix, rotations):
n = len(matrix)
# 计算实际需要进行的旋转次数
rotations = rotations % 4
for _ in range(rotations):
# 逐层进行旋转
for layer in range(n // 2):
first = layer
last = n - 1 - layer
for i in range(first, last):
offset = i - first
# 保存上边
top = matrix[first][i]
# 左边 -> 上边
matrix[first][i] = matrix[last-offset][first]
# 底边 -> 左边
matrix[last-offset][first] = matrix[last][last-offset]
# 右边 -> 底边
matrix[last][last-offset] = matrix[i][last]
# 上边 -> 右边
matrix[i][last] = top
return matrix
# 示例
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
rotated_matrix = rotateMatrix(matrix, 2)
print(rotated_matrix) # 输出 [[9, 8, 7], [6, 5, 4], [3, 2, 1]]
代码解释
rotateMatrix(matrix, rotations)函数接收两个参数:matrix: 待旋转的N阶方阵rotations: 旋转次数
- 函数内部首先计算实际需要旋转的次数 (
rotations % 4),因为每旋转4次就会回到初始状态。 - 然后,使用嵌套循环逐层进行旋转。外层循环控制旋转的层数,内层循环处理每一层中元素的移动。
- 在每一层的旋转过程中,使用
top变量暂存最上边元素的值,然后按照顺时针方向,将左边、底边、右边的元素依次向下一个位置移动。最后将top变量的值赋给右边元素,完成一次旋转。
示例分析
代码中给出的示例演示了如何使用 rotateMatrix 函数将一个3阶方阵 [[1, 2, 3], [4, 5, 6], [7, 8, 9]] 顺时针旋转两次。最终输出的结果为 [[9, 8, 7], [6, 5, 4], [3, 2, 1]],符合预期。
原文地址: https://www.cveoy.top/t/topic/IYY 著作权归作者所有。请勿转载和采集!