[돌머리] 돌머리를 깨기 위한 간단한 알고리즘 문제 – 매트릭스 90도 회전하기

Given an image represented by an NxN 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?

 

solve) Draw the mapping table. and easy you can find the rule

after 90 degrees rotation, map[y*n+x] ==> new_map(n-1-x)*n+y

and just write!!

 


#include <stdio.h>
#include <stdlib.h>

void printMap( int *map, int n ) {
 printf("=====map====\n");
 for( int y = 0; y < n; y++ ) {
 for( int x = 0; x < n; x++ ) {
 printf("%d ", map[y*n+x]);
 }
 printf("\n");
 }
}

void transform( int *map, int *new_map, int n )
{
 for( int y = n-1; y >= 0; y-- ){
 for( int x = 0 ; x < n; x++ ) {
 new_map[y*n+x] = map[(n-1-x)*n+y];
 }
 }
}

int main( int argc, char *argv[] ) {
 int n = atoi(argv[1]);

int *map = new int[n*n];
 for( int i = 0; i < n*n; i++ ) {
 map[i] = i;
 }

printMap(map, n);
 int *new_map = new int[n*n];
 transform(map, new_map, n);
 printMap(new_map, n);
 return 0;

}