我有這樣旋轉由n個步驟外基質
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]
我怎樣才能實現這一步的旋轉是動態的。
我發現這個解決方案,但這是固定的旋轉即ie。步= 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)
爲什麼不把你的旋轉矩陣多次調用來達到你想要的? –
我可以,但這不是一個通用的解決方案。 – unknown