首页 > 代码库 > CareerCup之1.6 Rotate Image

CareerCup之1.6 Rotate Image

【题目】

原文:

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?

译文:

一张图像表示成NxN的矩阵。图像中每一个像素是4个字节,写一个函数把图像旋转90度。 你能原地进行操作吗?(即不开辟额外的存储空间)

【分析】

点击打开链接

【代码一】

/*********************************
*   日期:2014-05-14
*   作者:SJF0115
*   题目: Rotate Image
*   来源:CareerCup
**********************************/
#include <iostream>
#include <algorithm>
#include <vector>
#include <string.h>
using namespace std;
//旋转图片
void RotateImage(vector<vector<int> > &matrix){
    int i,j,temp;
    int N = matrix.size();
    // 沿着副对角线反转
    for(i = 0; i < N;i++){
        for(j = 0;j < N - i;j++){
            temp = matrix[i][j];
            matrix[i][j] = matrix[N - 1 - j][N - 1 - i];
            matrix[N - 1 - j][N - 1 - i] = temp;
        }
    }
    // 沿着水平中线反转
    for(i = 0; i < N / 2;i++){
        for (j = 0; j < N;j++){
            temp = matrix[i][j];
            matrix[i][j] = matrix[N - 1 - i][j];
            matrix[N - 1 - i][j] = temp;
        }
    }
}

int main(){
    vector<int> row1 = {1,2,3};
    vector<int> row2 = {4,5,6};
    vector<int> row3 = {7,8,9};
    vector<vector<int>> matrix;
    matrix.push_back(row1);
    matrix.push_back(row2);
    matrix.push_back(row3);
    RotateImage(matrix);
    for(int i = 0;i < 3;i++){
        for(int j = 0;j < 3;j++){
            cout<<matrix[i][j]<<" ";
        }
        cout<<endl;
    }
    return 0;
}


【代码二】

/*********************************
*   日期:2014-05-14
*   作者:SJF0115
*   题目: Rotate Image
*   来源:CareerCup
**********************************/
#include <iostream>
#include <algorithm>
#include <vector>
#include <string.h>
using namespace std;
//旋转图片
void RotateImage(vector<vector<int> > &matrix){
    int layer,i,top;
    int n = matrix.size();
    //一层一层旋转
    for(layer = 0;layer < n/2;layer++){
        //第layer层第一个元素
        int first = layer;
        //第layer层最后一个个元素
        int last = n -1 - layer;
        for(i = first;i < last;i++){
            //偏移量
            int offset = i - first;
            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;
        }//for
    }//for
}

int main(){
    vector<int> row1 = {1,2,3};
    vector<int> row2 = {4,5,6};
    vector<int> row3 = {7,8,9};
    vector<vector<int>> matrix;
    matrix.push_back(row1);
    matrix.push_back(row2);
    matrix.push_back(row3);
    RotateImage(matrix);
    for(int i = 0;i < 3;i++){
        for(int j = 0;j < 3;j++){
            cout<<matrix[i][j]<<" ";
        }
        cout<<endl;
    }
    return 0;
}


CareerCup之1.6 Rotate Image