C - matrix rotation -
i'm writing program in c , need m x n
matrix rotate clockwise. tried algorithms, work in n x n
matrices.
the matrix {(1,4), (2,5), (3,6)}
should become {(3,2,1), (6,5,4)}
:
1 4 2 5 -> 3 2 1 3 6 6 5 4
i wrote piece of code transpose matrix, , don't know how swap columns:
void transpose(int matrix[max][max], int m, int n) { int transpose[max][max], d, c; (c = 0; c < m; c++) for( d = 0 ; d < n ; d++) transpose[d][c] = matrix[c][d]; (c = 0; c < n; c++) for(d = 0; d < m; d++) matrix[c][d] = transpose[c][d]; }
here's idea. i've implemented in java, should work in same manner in c. idea read array row major wise end, , fill other array column major wise, beginning.
int a[][]={{1,4},{2,5},{3,6}}; int m=3,n=2; //you need edit , calculate rows , 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(); }
output at: https://ideone.com/tveub5
Comments
Post a Comment