Home > 书山有路 > Question1.6: Rotate an NxN matrix by 90 degrees – Cracking the Coding Interview

Question1.6: Rotate an NxN matrix by 90 degrees – Cracking the Coding Interview

October 28th, 2011 Leave a comment Go to comments
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/*
 * question1-6.c
 *
 *  Created on: Oct 28, 2011
 *      Author: zhuhuang
 */
 
//Give 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?
 
//Solution1: Consider the matrix as embedded circles, we rotate the circle one by one until reaching the center.
//Solution2: Build another matrix with the same size, copy elements from one to the other according to a formula
 
//In this program, we use solution 1.
#include <stdio.h>
#define NUM 6
 
int arrayA[][5] = {{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}
                 };
 
int arrayB[][6] = {{1,2,3,4,5,-1},
                  {6,7,8,9,10,-1},
                  {11,12,13,14,15,-1},
                  {16,17,18,19,20,-1},
                  {21,22,23,24,25,-1},
                  {26,27,28,29,30,-1}
                 };
 
void printMatrix(int matrix[][NUM], int sidelength)
{
	int i, j;
	for(i=0;i<sidelength;i++)
	{
		for(j=0;j<sidelength;j++)
		{
			printf("%d ",matrix[i][j]);
		}
		printf("n");
	}
}
 
void AntiClockWiseRotate(int matrix[][NUM], int sidelength)
{
	int N = sidelength;
	int i=0, j=0;
	int temp;
 
	//matrix[i][j] (before rotation)  => matrix[N-1-j][i] (after rotation)
	//Consider the matrix as embedded circles, we rotate the circle one by one until reaching the center.
	//How many circles: N/2. When N%2=1, N/2+1 circles; when N%2=0, N/2 circles.
	for(i=0; i<N/2; i++){
		//Rotate a row cause rotating the circle.
		//A row in the circle: i ~ N-1-i. The element in (N-1-i) will be the one in (i) after rotation.
		for(j=i;j<N-1-i;j++){
			//when i==N-1-i, only one element in the circle (the center), do nothing. This happens when N%2!=0.
			temp = matrix[i][j];
			matrix[i][j] = matrix[j][N-1-i];
			matrix[j][N-1-i] = matrix[N-1-i][N-1-j];
			matrix[N-1-i][N-1-j] = matrix[N-1-j][i];
			matrix[N-1-j][i] = temp;
		}
	}
}
 
int main(void)
{
	if(NUM==5)
	{
		printf("Matrix A before ratation:n");
		printMatrix(arrayA, 5);
 
		AntiClockWiseRotate(arrayA,5);
 
		printf("Matrix A after ratation:n");
		printMatrix(arrayA, 5);
	}
 
	if(NUM==6)
	{
		printf("Matrix B before ratation:n");
		printMatrix(arrayB, 6);
 
		AntiClockWiseRotate(arrayB,6);
 
		printf("Matrix B after ratation:n");
		printMatrix(arrayB, 6);
	}
 
	return 1;
}
  1. No comments yet.
  1. No trackbacks yet.