将矩阵向右旋转 K 次的Java程序
给定一个大小为 N*M 的矩阵和一个数字 K。我们必须将矩阵向右旋转 K 次。
例子:
Input : N = 3, M = 3, K = 2
12 23 34
45 56 67
78 89 91
Output : 23 34 12
56 67 45
89 91 78
Input : N = 2, M = 2, K = 2
1 2
3 4
Output : 1 2
3 4
一种简单而有效的方法是将矩阵的每一行视为一个数组并执行数组旋转。这可以通过使用临时数组将元素从 K 复制到数组末尾到数组开头来完成。然后剩下的元素从开始到 K-1 到数组的结尾。
举个例子:
Java
// Java program to rotate a matrix
// right by k times
class GFG
{
// size of matrix
static final int M=3;
static final int N=3;
// function to rotate matrix by k times
static void rotateMatrix(int matrix[][], int k)
{
// temporary array of size M
int temp[]=new int[M];
// within the size of matrix
k = k % M;
for (int i = 0; i < N; i++)
{
// copy first M-k elements
// to temporary array
for (int t = 0; t < M - k; t++)
temp[t] = matrix[i][t];
// copy the elements from k
// to end to starting
for (int j = M - k; j < M; j++)
matrix[i][j - M + k] = matrix[i][j];
// copy elements from
// temporary array to end
for (int j = k; j < M; j++)
matrix[i][j] = temp[j - k];
}
}
// function to display the matrix
static void displayMatrix(int matrix[][])
{
for (int i = 0; i < N; i++)
{
for (int j = 0; j < M; j++)
System.out.print(matrix[i][j] + " ");
System.out.println();
}
}
// Driver code
public static void main (String[] args)
{
int matrix[][] = {{12, 23, 34},
{45, 56, 67},
{78, 89, 91}};
int k = 2;
// rotate matrix by k
rotateMatrix(matrix, k);
// display rotated matrix
displayMatrix(matrix);
}
}
// This code is contributed by Anant Agarwal.
输出:
23 34 12
56 67 45
89 91 78
请参阅完整的文章 Rotate the matrix right by K times 了解更多详情!