Created
June 23, 2014 23:38
-
-
Save xun-gong/78ced3e7837e5162bcde to your computer and use it in GitHub Desktop.
CareerCup1.6.cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Chapter 1 | |
* 1.6 Given an image represented by an N*N 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? | |
*/ | |
/* Rotate 90 degree counter-clockwise */ | |
#include <iostream> | |
using namespace std; | |
#define N 4 | |
// Rotate by Swap | |
void rotate1(int matrix[][N]) | |
{ | |
int layer = N/2; // top_left_right_bottom | |
for (int i = 0; i < layer; ++i) | |
{ | |
int begin = i; // iteration begin index | |
int end = N - 1 - i; // iteration end index | |
for (int j = begin; j < end; j++) | |
{ | |
// About the subscripts, you have to induct from small examples | |
// save top | |
int top = matrix[i][j]; | |
// right -> top | |
matrix[i][j] = matrix[j][end]; | |
// bottom -> right | |
matrix[j][end] = matrix[end][end - j + begin]; | |
// left -> bottom | |
matrix[end][end - j + begin] = matrix[end - j + begin][begin]; | |
// top -> left | |
matrix[end - j + begin][begin] = top; | |
} | |
} | |
} | |
/* Rotate 90 degree clockwise */ | |
// Rotate by Flip | |
void rotate2(int matrix[][N]) | |
{ | |
// diagonal flip | |
for (int i = 0; i < N; ++i) | |
{ | |
for (int j = 0; j < N; ++j) | |
{ | |
if (i < j) | |
{ | |
int tmp = matrix[i][j]; // save upper right tri-angle area | |
matrix[i][j] = matrix[j][i]; // assign lower left to upper right tri-angle area | |
matrix[j][i] = tmp; // assign upper right to lower left tri-angle area | |
} | |
} | |
} | |
// vertical middle line flip | |
for (int j = 0; j < N/2; ++j) | |
{ | |
for (int i = 0; i < N; ++i) | |
{ | |
int tmp = matrix[i][j]; // save left | |
matrix[i][j] = matrix[i][N - j - 1]; // assign right to left | |
matrix[i][N - j - 1] = tmp; // assign left to right | |
} | |
} | |
} | |
// Main | |
int main(int argc, char const *argv[]) | |
{ | |
int matrix [N][N] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}; | |
// int matrix [N][N] = {{1, 2}, {3, 4}}; | |
rotate2(matrix); | |
for (int i = 0; i < N; ++i) { | |
for (int j = 0; j < N; ++j) { | |
cout << matrix[i][j] << " "; | |
if (j == N - 1) { | |
cout << endl; | |
} | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment