Last active
December 14, 2015 03:09
-
-
Save ThunderXu/5018599 to your computer and use it in GitHub Desktop.
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?
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
#include <iostream> | |
#include <fstream> | |
bool ReadFile(int**, int); | |
void Output(int**, int); | |
void Rotate(int**, int, int); | |
int main() | |
{ | |
using namespace std; | |
cout<<"Enter the size please"<<endl; | |
int size; | |
cin>>size; | |
//Construct the matrix | |
if(size>0) | |
{ | |
int **mat = new int*[size]; | |
for(int i=0;i<size;i++) | |
{ | |
mat[i] = new int[size]; | |
} | |
if(ReadFile(mat, size)) | |
{ | |
Rotate(mat,size,0); | |
Output(mat,size); | |
} | |
//delete | |
for(int i=0;i<size;i++) | |
{ | |
delete[] mat[i]; | |
} | |
delete[] mat; | |
} | |
} | |
//Read Matrix from file | |
bool ReadFile(int **mat, int size) | |
{ | |
using namespace std; | |
ifstream ifile; | |
ifile.open("input.txt"); | |
if(!ifile) | |
{ | |
cout<<"Open Unsuccess"<<endl; | |
return false; | |
} | |
for(int i=0;i<size;i++) | |
{ | |
for(int j=0;j<size;j++) | |
{ | |
ifile>>mat[i][j]; | |
} | |
} | |
return true; | |
} | |
//Output the result through console | |
void Output(int **mat, int size) | |
{ | |
using namespace std; | |
for(int i=0;i<size;i++) | |
{ | |
for(int j=0;j<size;j++) | |
{ | |
cout<<mat[i][j]<<" "; | |
} | |
cout<<endl; | |
} | |
} | |
//Rotate the matrix, direction means clock-wise or not | |
void Rotate(int **mat, int size, int direction) | |
{ | |
using namespace std; | |
for(int i=0;i<size/2;i++) | |
{ | |
for(int j=i;j<size-i-1;j++) | |
{ | |
switch(direction) | |
{ | |
case 0: | |
{ | |
int temp = mat[j][size-1-i]; | |
mat[j][size-1-i]=mat[i][j]; | |
mat[i][j]=mat[size-1-j][i]; | |
mat[size-1-j][i]=mat[size-1-i][size-1-j]; | |
mat[size-1-i][size-1-j]=temp; | |
break; | |
} | |
case 1: | |
{ | |
int temp = mat[i][j]; | |
mat[i][j]=mat[j][size-1-i]; | |
mat[j][size-1-i]=mat[size-1-i][size-1-j]; | |
mat[size-1-i][size-1-j]=mat[size-1-j][i]; | |
mat[size-1-j][i]=temp; | |
break; | |
} | |
default: | |
break; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment