Q1.6 To rotate a image by 90 degress.

来源:互联网 发布:java特种兵.pdf 编辑:程序博客网 时间:2024/05/20 07:16

Q: Given an image represented by an NxN matrix, where each pixel in theimage is 4 bytes, write a method to rotate the image by 90 degrees.Can you do this in place?

A:

思路一:第一步交换主对角线两侧的对称元素,第二步交换第i行和第n-1-i行。即先交换主对角线对称的元素,在交换关于水平N/2线对称的元素。

思路二: 逐层旋转。 上->右, 右->下, 下->左, 左->上


#include<iostream>#include<vector>using namespace std;void swap(int &a, int &b){    int t = a;    a = b;    b = t;}void rotateImage1(int matrix[][4], int n) {    for (int i = 0; i < n; i++) {        for (int j = 0; j < n - 1 - i; j++ ) {            swap(matrix[i][j], matrix[n-j-1][n-i-1]);        }    }    for (int i = 0; i < n/2; i++) {        for (int j = 0; j < n; j++) {            swap(matrix[i][j], matrix[n-1-i][j]);        }    }    return ;}void rotateImage2(int matrix[][4], int 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;int top = matrix[first][i];matrix[first][i] = matrix[last-offset][first];matrix[last-offset][first] = matrix[last][last - offset];matrix[last][last - offset] = matrix[i][last];matrix[i][last] = top;}}}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;    rotateImage2(a, 4);    for(int i=0; i<4; ++i){        for(int j=0; j<4; ++j)            cout<<a[i][j]<<" ";        cout<<endl;    }    return 0;}


0 0