2019년 4월 13일 토요일

# 주어진 정사각형 이미지 시계방향 90' 회전

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <iostream>

/*
 참고 문서.
 1. http://stackoverflow.com/questions/2680738/howto-transpose-multidimensional-array-in-place
 2. http://stackoverflow.com/questions/42519/how-do-you-rotate-a-two-dimensional-array
 3. http://www.math-only-math.com/90-degree-clockwise-rotation.html
*/

void Solution(int* image, int width);
void PrintImage(int* image, int width);
int main() {         
 int image[] = { 1, 2, 3, 
     4, 5, 6,
     7, 8, 9 };
 int image2[] = { 1,2,3,4,
     5,6,7,8,
     9,10,11,12,
     13,14,15,16};
 int image3[] = { 1,2,3,4,5,
     6,7,8,9,10,
     11,12,13,14,15,
     16,17,18,19,20,
     21,22,23,24,25 };
 PrintImage(image3, 5);
 Solution(image3, 5);
 PrintImage(image3, 5);
 // ..
}

void Solution(int* image, int width) { 
 int height = width;
 //transpose
 for (int x = 0; x < width; x++) {
  for (int y = 0; y < x; y++) {
   int tmp = image[x * width + y];
   image[x * width + y] = image[x + width * y];
   image[x + width * y] = tmp;
  }
 }
 // reverse each rows.
 int sizeOfImage = width * height;
 int numberOfSwap = width / 2;
 for (int rowStep = 0, rowNum = 1; rowStep < sizeOfImage; rowStep += width, rowNum++) {
  int eachRowEnd = width * rowNum;
  for (int idx = 1; idx <= numberOfSwap; idx++) {
   int pixelIdx = rowStep + idx -1;
   int tmp = image[pixelIdx];
   image[pixelIdx] = image[eachRowEnd - idx];
   image[eachRowEnd - idx] = tmp;
  }
 }
}

void PrintImage(int* image, int width) {
 int sizeOfImage = width * width;
 std::cout << std::endl << "-------------------------";
 for (int i = 0; i < sizeOfImage; i++) {
  if (i % width == 0) std::cout << std::endl;
  std::cout << image[i] << ",";
 }
}

댓글 없음:

댓글 쓰기