我正在用 C 编写一个程序,我需要一个 M x N 矩阵来顺时针旋转。我尝试了一些算法,但它们只适用于 N x N 矩阵。
矩阵 {(1,4), (2,5), (3,6)}
应变为 {(3,2,1), (6,5, 4)}
:
1 4
2 5 -> 3 2 1
3 6 6 5 4
我写了这段代码来转置矩阵,但现在我不知道如何交换列:
void transpose(int matrix[MAX][MAX], int m, int n)
{
int transpose[MAX][MAX], d, c;
for (c = 0; c < m; c++)
for( d = 0 ; d < n ; d++)
transpose[d][c] = matrix[c][d];
for (c = 0; c < n; c++)
for(d = 0; d < m; d++)
matrix[c][d] = transpose[c][d];
}
最佳答案
这是一个想法。我已经在 Java 中实现了它,但它在 C 中应该以相同的方式工作。这个想法是从末尾开始主要读取数组行,并从头开始主要填充其他数组列 em>.
int a[][]={{1,4},{2,5},{3,6}};
int m=3,n=2; //you will need to edit this and actually calculate rows and columns.
int b[][]=new int[n][m];
for(int i=m-1; i>=0; i--)
for(int j=0; j<n; j++)
b[j][m-i-1]=a[i][j];
for(int i=0; i<n; i++) {
for(int j=0; j<m; j++)
System.out.print(b[i][j]+"\t");
System.out.println();
}
关于C - 矩阵旋转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30647682/