Rotate Matrix

#include <iostream>

using namespace std;

#define N 4

void rotate90(int (*a)[N], int st, int ed) {
       if(st >= ed) return;
       int tmp;
       for(int i = 0 ; i < ed-st; i++) { // index start from zero
              // Note the rotate order
              tmp = a[st][i+st];
              a[st][i+st] = a[ed-i][st];
              a[ed-i][st] = a[ed][ed-i];
              a[ed][ed-i] = a[i+st][ed];
              a[i+st][ed] = tmp;
       }
       rotate90(a, st+1, ed-1);
}

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

       //print
       for(int i = 0; i<N; i++) {
              for(int j = 0; j<N; j++)
                     cout<<a[i][j]<<", ";
              cout<<endl;
       }

}

Comments

Popular posts from this blog

Unique Binary Search Trees

Coin in Line