1
+ /*
2
+ * You are given an n x n 2D matrix representing an image.
3
+
4
+ * Rotate the image by 90 degrees (clockwise).
5
+
6
+ * Follow up:
7
+ * Could you do this in-place?
8
+ * Created by supercoderx on 2017/8/14.
9
+ */
10
+ #include
11
+ #include
12
+
13
+ void rotate (int * * matrix , int matrixRowSize , int matrixColSize ) {
14
+ int tmp ;
15
+ for (int i = 0 ; i < matrixRowSize / 2 ; i ++ ) {
16
+ if (2 * i == matrixRowSize - 1 )
17
+ break ;
18
+ for (int j = i ; j < matrixRowSize - i - 1 ; j ++ ) {
19
+ // 上<->右
20
+ tmp = matrix [i ][j ];
21
+ matrix [i ][j ] = matrix [j ][matrixRowSize - 1 - i ];
22
+ matrix [j ][matrixRowSize - 1 - i ] = tmp ;
23
+ // 下<->左
24
+ tmp = matrix [matrixRowSize - 1 - j ][i ];
25
+ matrix [matrixRowSize - 1 - j ][i ] = matrix [matrixRowSize - 1 - i ][matrixColSize - 1 - j ];
26
+ matrix [matrixRowSize - 1 - i ][matrixColSize - 1 - j ] = tmp ;
27
+ // 上<->下
28
+ tmp = matrix [i ][j ];
29
+ matrix [i ][j ] = matrix [matrixColSize - 1 - i ][matrixRowSize - 1 - j ];
30
+ matrix [matrixColSize - 1 - i ][matrixRowSize - 1 - j ] = tmp ;
31
+ }
32
+ }
33
+ }
34
+
35
+ void testRotate () {
36
+ int count = 3 , * * matrix = malloc (sizeof (int * ) * count );
37
+ matrix [0 ] = malloc (sizeof (int ) * count );
38
+ matrix [1 ] = malloc (sizeof (int ) * count );
39
+ matrix [2 ] = malloc (sizeof (int ) * count );
40
+ //matrix[3] = malloc(sizeof(int)*count);
41
+ //matrix[4] = malloc(sizeof(int)*count);
42
+
43
+ for (int k = 0 ; k < count ; ++ k ) {
44
+ for (int i = 0 ; i < count ; ++ i ) {
45
+ matrix [k ][i ] = k * count + i + 1 ;
46
+ }
47
+ }
48
+ rotate (matrix , count , count );
49
+ for (int i = 0 ; i < count ; i ++ ) {
50
+ for (int j = 0 ; j < count ; ++ j ) {
51
+ printf ("%d," , matrix [i ][j ]);
52
+ }
53
+ printf ("\n" );
54
+ }
55
+
56
+
57
+ }
0 commit comments