Python3程序将除对角线以外的所有矩阵元素顺时针旋转K次90度
给定一个维度为N的方阵mat[][]和一个整数K ,任务是在不改变对角元素位置的情况下将矩阵旋转 90 度K次。
例子:
Input: mat[][] = {{1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}, {11, 12, 13, 14, 15}, {16, 17, 18, 19, 20}, {21, 22, 23, 24, 25}}, K = 1
Output:
1 16 11 6 5
22 7 12 9 2
23 18 13 8 3
24 17 14 19 4
21 20 15 10 25
Input: mat[][] = {{10, 11}, {12, 13}}, K = 2
Output:
10 11
12 13
方法:给定的问题可以通过使用本文讨论的思想和矩阵在执行顺时针旋转 4 次后恢复的事实来解决。请按照以下步骤解决给定的问题:
- 将 K 的值更新为K % 4 。
- 迭代直到K为正数并执行以下步骤:
- 遍历矩阵,对于i在[0, N / 2)范围内和j在[0, N – i – 1)范围内并执行以下步骤:
- 如果i != j和(i + j) != (N – 1)的值,则执行以下步骤:
- 将mat[i][j]的值存储在临时变量temp中。
- 将mat[i][j]的值更新为mat[N – 1 – j][i] 。
- 将mat[N – 1 – j][i]的值更新为mat[N – 1 -i][N – 1 – j] 。
- 将mat[N – 1 – i][N – 1 – j]的值更新为mat[j][N – 1 – i] 。
- 将mat[j][N – 1 – i]的值更新为temp 。
- 完成上述步骤后,打印得到的更新矩阵。
下面是上述方法的实现:
Python3
# Python3 program for the above approach
# Function to print the matrix
def printMat(mat):
# Iterate over the rows
for i in range(len(mat)):
# Iterate over the columns
for j in range(len(mat[0])):
# Print the value
print(mat[i][j], end = " ")
print()
# Function to perform the swapping of
# matrix elements in clockwise manner
def performSwap(mat, i, j):
N = len(mat)
# Stores the last row
ei = N - 1 - i
# Stores the last column
ej = N - 1 - j
# Perform the swaps
temp = mat[i][j]
mat[i][j] = mat[ej][i]
mat[ej][i] = mat[ei][ej]
mat[ei][ej] = mat[j][ei]
mat[j][ei] = temp
# Function to rotate non - diagonal
# elements of the matrix K times in
# clockwise direction
def rotate(mat, N, K):
# Update K to K % 4
K = K % 4
# Iterate until K is positive
while (K > 0):
# Iterate each up to N/2-th row
for i in range(int(N / 2)):
# Iterate each column
# from i to N - i - 1
for j in range(i, N - i - 1):
# Check if the element
# at i, j is not a
# diagonal element
if (i != j and (i + j) != N - 1):
# Perform the swapping
performSwap(mat, i, j)
K -= 1
# Print the matrix
printMat(mat)
# Driver Code
K = 5
mat = [ [ 1, 2, 3, 4 ],
[ 6, 7, 8, 9 ],
[ 11, 12, 13, 14 ],
[ 16, 17, 18, 19 ] ]
N = len(mat)
rotate(mat, N, K)
# This code is contributed by Dharanendra L V.
输出:
1 11 6 4
17 7 8 2
18 12 13 3
16 14 9 19
时间复杂度: O(N 2 )
辅助空间: O(1)
请参阅完整的文章关于将除对角线 K 次以外的所有矩阵元素顺时针方向旋转 90 度以获取更多详细信息!