Cracking the coding interview 题目
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?
译文:
一张图像表示成NxN的矩阵,图像中每个像素是4个字节,写一个函数把图像旋转90度。 你能原地进行操作吗?(即不开辟额外的存储空间)
译文:
一张图像表示成NxN的矩阵,图像中每个像素是4个字节,写一个函数把图像旋转90度。 你能原地进行操作吗?(即不开辟额外的存储空间)
解决思路比较简单:
首先将整个图当做一个 int型的矩阵,这样,首先将这个整数矩阵沿着右上左下方向的对角线进行翻转,在对整个矩阵进行上下翻转即可得到想要的结果。
#include <iostream>
using namespace std;
#define N 4
int main()
{
int array[N][N];
for(int i = 0; i < N; i++)
{
for(int j = 0; j < N; j++)
{
array[i][j] = i * N + j + 1;
}
}
cout << "反转前:" << endl;
for(int i = 0; i < N; i++)
{
for(int j = 0; j < N; j++)
{
cout << array[i][j] << "\t";
}
cout << endl;
}
cout << endl;
cout << endl;
// 先进行对角线翻转
for(int i = 0; i < N; i++)
{
for(int j = 0; j < i; j++)
{
array[i][j] ^= array[j][i];
array[j][i] ^= array[i][j];
array[i][j] ^= array[j][i];
}
}
// 再进行上下翻转
for(int i = 0; i < N / 2; i++)
{
for(int j = 0; j < N; j++)
{
array[i][j] ^= array[N-1-i][j];
array[N-1-i][j] ^= array[i][j];
array[i][j] ^= array[N-1-i][j];
}
}
cout << "反转后:" << endl;
for(int i = 0; i < N; i++)
{
for(int j = 0; j < N; j++)
{
cout << array[i][j] << "\t";
}
cout << endl;
}
return 0;
}