Rotated Matrix

/***
Given an image represented by an N*N matrix, where each pixel in the image is 4 bytes, write a method to rotate the image by 90 degrees. Can you do this in place?
int - 4bytes
***/

/***
complexity O(N2)
a[i][j] -> a[j][sz-1-i]
a[j][sz-1-i] -> a[sz-1-i][sz-1-j]
a[sz-1-i][sz-1-j] -> a[sz-1-j][i]
a[sz-1-j][i] -> a[i][j]

(0,0) -> (0,n)
(0,n) -> (n,n)
(n,n) -> (n,0)
(n,0) -> (0,0)

trick: inner loop should be looped less than size..to avoid double rotate for the edge
***/


#include <iostream>

using namespace std;

void rotate90(int (*a)[4], int sz) {

int temp;
for(int i = 0; i < sz/2; i++) {
for(int j = i; j < sz-2*i-1; j++) {
temp = a[i][j];
a[i][j] = a[sz-1-j][i];
a[sz-1-j][i] = a[sz-1-i][sz-1-j];
a[sz-1-i][sz-1-j] = a[j][sz-1-i];
a[j][sz-1-i] = temp;
}
}
}


void print(int (*a)[4], int sz) {
for(int i=0; i<sz; i++) {
for(int j=0; j<sz; j++)
cout<<a[i][j]<<" ";
cout<<endl;
}
}

void main () {
int a[][4] = {{1,2,3,4}, {5,6,7,8}, {9,10,11,12}, {13,14,15,16}};
print(a, 4);
cout<<endl;
rotate90(a, 4);
print(a, 4);
}

Comments

Popular posts from this blog

Sudoku

Longest prefix matching - trie

Climbing Stairs