Skip to content

Instantly share code, notes, and snippets.

@frank4565
Last active August 29, 2015 13:56
Show Gist options
  • Save frank4565/8952190 to your computer and use it in GitHub Desktop.
Save frank4565/8952190 to your computer and use it in GitHub Desktop.
1.6 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?
#include<iostream>
using namespace std;
const int N = 4;
void rotate(int matrix[][N])
{
for (int i = 0; i < N/2; i++) {
for (int j = i; j < N-1-i; j++) {
int temp = matrix[i][j];
matrix[i][j] = matrix[N-1-j][i];
matrix[N-1-j][i] = matrix[N-1-i][N-1-j];
matrix[N-1-i][N-1-j] = matrix[j][N-1-i];
matrix[j][N-1-i] = temp;
}
}
}
void rotate0(int matrix[][N])
{
for (int layer = 0; layer < N/2; layer++) {
int first = layer;
int last = N-1-layer;
for (int i = first; i < last; i++) {
int offset = i - first;
// save top
int top = matrix[first][i];
// left -> top
matrix[first][i] = matrix[last-offset][first];
// bottom -> left
matrix[last-offset][first] = matrix[last][last-offset];
// right -> bottom
matrix[last][last-offset] = matrix[i][last];
// top -> right
matrix[i][last] = top;
}
}
}
void print(int matrix[][N])
{
for (int nRow = 0; nRow < N; nRow++)
{
for (int nCol = 0; nCol < N; nCol++)
cout << matrix[nRow][nCol] << "\t";
cout << endl;
}
}
int main(int argc, char *argv[])
{
int m[][N]{{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
print(m);
cout << endl;
rotate(m);
print(m);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment