Rotate Image

You are given an n x n 2D matrix representing an image.

Rotate the image by 90 degrees (clockwise).

Follow up:
Could you do this in-place?

一圈一圈的调整,关键是找到变换的各个坐标的关系,行变列,而行中第一个数在列中为第一个数,第二个数再列中为第二个数...第n个数在列中为第n个数;列变行,列中第一个数变为行中最后一个数,第二个数变为倒数第二个,第三变倒数第三....最后一个变为行的第一个数。

一:以下代码从列边行的角度出发写的,也就是从后往前推。

class Solution {
public:
    void rotateSquare(vector<vector<int>>& matrix,int leftup,int rightdown)
    {
        int diff = rightdown-leftup;
        for(int i=0;i<diff;i++){
            int tmp = matrix[leftup][leftup+i];
            matrix[leftup][leftup+i] = matrix[rightdown-i][leftup];//列变行
            matrix[rightdown-i][leftup] = matrix[rightdown][rightdown-i];//行变列
            matrix[rightdown][rightdown-i] = matrix[leftup+i][rightdown];//列变行
            matrix[leftup+i][rightdown] = tmp;
        }
    }
    void rotate(vector<vector<int>>& matrix) {
        int row = matrix.size();
        if(row==0){
            return;
        }
        int i=0;
        while(i<row){
            rotateSquare(matrix,i,row-1);
            i++;
            row--;
        }
    }
};

 二:以下从行变列出发写,也就是从前往后推。

class Solution {
public:
    void rotateSquare(vector<vector<int>>& matrix,int leftup,int rightdown)
    {
        int diff = rightdown-leftup;
        for(int i=0;i<diff;i++){
            int tmp1 = matrix[leftup+i][rightdown];
            matrix[leftup+i][rightdown] = matrix[leftup][leftup+i];
            int tmp2 = matrix[rightdown][rightdown-i] ;
            matrix[rightdown][rightdown-i] = tmp1;
            tmp1 = matrix[rightdown-i][leftup];
            matrix[rightdown-i][leftup]=tmp2;
            matrix[leftup][leftup+i] = tmp1;
        }
    }
    void rotate(vector<vector<int>>& matrix) {
        int row = matrix.size();
        if(row==0){
            return;
        }
        int i=0;
        while(i<row){
            rotateSquare(matrix,i,row-1);
            i++;
            row--;
        }
    }
};

 

posted @ 2015-11-12 21:21  zengzy  阅读(187)  评论(0编辑  收藏  举报
levels of contents