您的位置:首页 > 其它

Cracking The Coding Interview 1.6

2014-04-03 09:45 344 查看
//原文:
//
//	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;
void swap(int &a, int &b)
{
int t=a;
a=b;
b=t;
}
void replace(int **matrix, int size)
{
for (int i = 0;i<size; i++)
{
for (int j=i;j<size; j++)
{
swap(matrix[i][j],matrix[j][i]);
}
}

for (int i = 0; i<size/2; i++)
{
for (int j=0;j<size; j++)
{
swap(matrix[i][j],matrix[size-1-i][j]);
}
}
}
void display(int **matrix, int size)
{
for (int k = 0; k<size; k++)
for (int t = 0; t<size; t++)
{
cout<<matrix[k][t];
if (t==size-1)
{
cout<<endl;
}
}
}
int main()
{
int size = 4;
int **p = new int *[size];
for (int i=0; i<size; i++)
{
p[i] = new int[size];
}

for (int k = 0; k<size; k++)
for (int t = 0; t<size; t++)
{
p[k][t] = 2*k+t;
}
display(p,size);
replace(p,size);
cout<<endl;
display(p,size);

int a=3,b=4;
swap(a,b);

for (int k=0;k<size;k++)
{
delete [] p[k];
}
delete p;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: