Monday, August 13, 2012

Rotating a N X N matrix clockwise by 90 degrees


#include<stdio.h>
#define N 4

void display(int A[][N]){
int i,j;
for(i=0;i<N;i++){
for(j=0;j<N;j++){
printf("%d\t",A[i][j]);
}
printf("\n");
}
}

void rotate(int A[][N]){
int i,j;
int temp;
for(j=0;j<N/2;j++){
for(i=0;i<N-1-2*j;i++){
temp = A[j][i+j];
A[j][i+j] = A[N-1-i-j][j];
A[N-1-i-j][j] = A[N-1-j][N-1-i-j];
A[N-1-j][N-1-i-j] = A[i+j][N-1-j];
A[i+j][N-1-j] = temp;
}
}
}

int main(){
int A[N][N] = {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
//int A[N][N] = {{1,2,3},{4,5,6},{7,8,9}};
printf("original matrix :\n");
display(A);
rotate(A);
printf("after rotating 90deg clockwise :\n");
display(A);
return 0;
}

No comments:

Post a Comment