Created
March 3, 2014 18:27
-
-
Save vo/9331392 to your computer and use it in GitHub Desktop.
Rotating an NxN array 90 degrees in-place with a transpose and flip operation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <cstdio> | |
#define DIM 5 | |
void swap(int s[DIM][DIM], int i, int j, int k, int l) { | |
char c = s[i][j]; | |
s[i][j] = s[k][l]; | |
s[k][l] = c; | |
} | |
void print_matrix(int s[DIM][DIM]) { | |
for(int i=0; i<DIM; ++i) { | |
for(int j=0; j<DIM; ++j) | |
printf("%d ", s[i][j]); | |
printf("\n"); | |
} | |
} | |
void rotate(int s[DIM][DIM]) { | |
// perform transpose | |
for(int i=0; i<DIM; ++i) | |
for(int j=i+1; j<DIM; ++j) | |
swap(s,i,j,j,i); | |
// perform vertical flip | |
for(int i=0; i<DIM; ++i) | |
for(int j=0; j<DIM/2; ++j) | |
swap(s,i,j,i,DIM-j-1); | |
} | |
int main() { | |
// initialize a matrix | |
int s[DIM][DIM]; | |
for(int i=0, k=1; i<DIM; ++i) | |
for(int j=0; j<DIM; ++j, ++k) | |
s[i][j] = k; | |
puts("Before:"); | |
print_matrix(s); | |
rotate(s); | |
puts("After:"); | |
print_matrix(s); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment