Rotated Matrix


NOTE: 思维缺乏严谨!!! 要注意细节!!!
/**
2D matric rotation

recursive solve start from r=0 c(0~n-1) c=0 r(0~n-1)
next r=1 c(1~n-1) c=1 r(1~n-1)

complexity O(mn)
***/

#include<iostream>
using namespace std;

#define N 3

void swap(int *a, int *b) {
       int t;
       t = *a;
       *a = *b;
       *b = t;
}

void rotate2D(int (*a)[N], int index) {
       //base case
       if(index == N-1) return;

       for(int i = index; i<N; i++) {
              swap(&(a[i][index]), &(a[index][i]));
       }
       rotate2D(a, index+1);
}

void rotate1D(int *a, int index) {
       //base case
       if (index == N-1) return;
       for(int i = index; i<N; i++) {
              swap(a+i*N+index, a+index*N+i);
       }
       rotate1D(a, index+1);
}

void main() {
       int a[][N] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
       int a1[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
       rotate2D(a, 0);
       rotate1D(a1,0);
       for(int i = 0, k=0; i<N, k<N*N; i++) {
              for(int j = 0; j<N; j++)
                     cout<<a[i][j]<<"|"<<a1[k++]<<", ";
              cout<<endl;
       }

}

Comments

Popular posts from this blog

Sudoku

Longest prefix matching - trie

Climbing Stairs