1.6

给定一副N*N矩阵的图像,其中每个像素的大小为4字节,编写方法,将图像旋转90度,不占用额外的内存空间,是否做到?

* 步骤1

* 步骤2

可以分两步走。 第一步交换主对角线两侧的对称元素,第二步交换第i行和第n-1-i行,即得到结果。

* 代码

#include <iostream>
using namespace std;

void swap(int &a, int &b){
int t = a;
a = b;
b = t;
}
void transpose(int a[][4], int n){
for(int i=0; i<n; ++i)
for(int j=i+1; j<n; ++j)
swap(a[i][j], a[j][i]);
for(int i=0; i<n/2; ++i)
for(int j=0; j<n; ++j)
swap(a[i][j], a[n-1-i][j]);
}
int main(){
int a[4][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16}
};
for(int i=0; i<4; ++i){
for(int j=0; j<4; ++j)
cout<<a[i][j]<<" ";
cout<<endl;
}
cout<<endl;
transpose(a, 4);
for(int i=0; i<4; ++i){
for(int j=0; j<4; ++j)
cout<<a[i][j]<<" ";
cout<<endl;
}
return 0;
}

results matching ""

    No results matching ""