首页 > 代码库 > [leetcode]Rotate Image

[leetcode]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?


基本思路:

此题要求矩阵顺时针转90度。可以找出元素选择规律:

i‘ = j;

j‘ = n-1-i;

i,j 位置的元素旋转后应该到i‘,j‘位置。

最基本的解法可以借助与一个副本matrix。如不不利用副本,可以将对位位置的四个元素一个一个的替换。具体请结合代码查看。


代码:

    void rotate(vector<vector<int> > &matrix) {
        int n = matrix.size();
        
        int low = 0,high = n-1,j = 0;
        while(low < high){
            int tmpi,tmpj,value1,value2,tmp_i,tmp_j;
            for(int i = low ; i < high; i++){
                //1
                tmp_i = i;
                tmp_j = j;
                tmpi = tmp_j;
                tmpj = n-1-tmp_i;
                value1 = matrix[tmpi][tmpj];
                matrix[tmpi][tmpj] =matrix[i][j];
                //2
                tmp_i = tmpi;
                tmp_j = tmpj;
                tmpi = tmp_j;
                tmpj = n-1-tmp_i;
                value2= value1;
                value1 = matrix[tmpi][tmpj];
                matrix[tmpi][tmpj] =value2;
                
                //3
                tmp_i = tmpi;
                tmp_j = tmpj;
                tmpi = tmp_j;
                tmpj = n-1-tmp_i;
                value2 = value1;
                value1 = matrix[tmpi][tmpj];
                matrix[tmpi][tmpj] = value2;
                
                //4
                tmp_i = tmpi;
                tmp_j = tmpj;
                tmpi = tmp_j;
                tmpj = n-1-tmp_i;
                value2 =value1;
                value1 = matrix[tmpi][tmpj];
                matrix[tmpi][tmpj] = value2;
            }
            low++;
            high--;
            j++;
        }
    }


[leetcode]Rotate Image