【发布时间】:2025-12-23 14:25:17
【问题描述】:
我有一个像
这样的矩阵matrix1 = [1,2
3,4]
matrix2 =[1,2,3
4,5,6
7,8,9]
我想像 r=1 这样按某个步长旋转这个矩阵,然后输出就像
output_matrix = [3,1
4,2]
output_matrix = [4,1,2
7,5,3
8,9,6]
我怎样才能做到这一点,步骤的旋转将是动态的。
我找到了这个解决方案,但这是用于固定旋转,即。步=1
def rotateMatrix(mat):
if not len(mat):
return
top = 0
bottom = len(mat)-1
left = 0
right = len(mat[0])-1
while left < right and top < bottom:
# Store the first element of next row,
# this element will replace first element of
# current row
prev = mat[top+1][left]
# Move elements of top row one step right
for i in range(left, right+1):
curr = mat[top][i]
mat[top][i] = prev
prev = curr
top += 1
# Move elements of rightmost column one step downwards
for i in range(top, bottom+1):
curr = mat[i][right]
mat[i][right] = prev
prev = curr
right -= 1
# Move elements of bottom row one step left
for i in range(right, left-1, -1):
curr = mat[bottom][i]
mat[bottom][i] = prev
prev = curr
bottom -= 1
# Move elements of leftmost column one step upwards
for i in range(bottom, top-1, -1):
curr = mat[i][left]
mat[i][left] = prev
prev = curr
left += 1
return mat
matrix =[[1,2,3],[4,5,6], [7,8,9]]
matrix = rotateMatrix(matrix)
# # Print modified matrix
print(matrix)
【问题讨论】:
-
为什么不多次调用你的旋转矩阵来达到你想要的效果呢?
-
我可以,但这不是一个通用的解决方案。
标签: python python-2.7 python-3.x matrix