Skip to content

Instantly share code, notes, and snippets.

@vo
Created March 3, 2014 18:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vo/9331392 to your computer and use it in GitHub Desktop.
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
#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