Categories
不学无术

48. Rotate Image

思路

剥洋葱一样的过程可以实现原位替换,只要一个最大为n的暂存数组就行了。

0, 1, 2, 3
4, 5, 6, 7
8, 9, A, B
C, D, E, F

这么个矩阵,首先从最外面一圈剥起,将[0,1,2]记录下来,然后替换为[C,8,4];然后顺时针继续,将[3,7,B]记录下来,然后用刚才记住的[0,1,2]替换…

代码

class Solution {
public:
    void rotate(vector<vector<int>>& matrix) {
        int floor = 0;
        int ceiling = matrix.size() - 1;
        if(ceiling < 0)
            return; //empty
        vector<int> temp;
        while(floor < ceiling){
            //up
            for(int col=floor; col<ceiling; col++){
                temp.push_back(matrix[floor][col]); //remember current
                matrix[floor][col] = matrix[ceiling-(col-floor)][floor]; //replace with left column values
            }
            //right
            for(int row=floor; row<ceiling; row++){
                temp.push_back(matrix[row][ceiling]);  //remember current
                matrix[row][ceiling] = temp[0]; //replace
                temp.erase(temp.begin());
            }
            //bottom
            for(int col=ceiling; col>floor; col--){
                temp.push_back(matrix[ceiling][col]);
                matrix[ceiling][col] = temp[0];
                temp.erase(temp.begin());
            }
            //left
            for(int row=ceiling; row>floor; row--){
                matrix[row][floor] = temp[0];
                temp.erase(temp.begin());
            }
            floor++;
            ceiling--;
        }
    }
};

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.