Wednesday, August 12, 2015

Leetcode: Rotate Image (4ms)

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?

Analysis:
Rotate through triangle first (slash direction) and then rotate through middle of row. 

/////////////////////////////////////////
//code 4ms
class Solution {
public:
    void rotate(vector<vector<int>>& matrix) {
        int n = matrix.size();
        for(int i=0;i<n;i++){
            for(int j=0;j<n-i-1;j++){
                swap(matrix[i][j],matrix[n-j-1][n-i-1]);//rotate through diagonal  
            }
        }
        for(int i=0;i<n/2;i++){
            for(int j=0;j<n;j++){
                swap(matrix[i][j],matrix[n-i-1][j]);//rotate through middle of row
            }
        }
    }
};

No comments:

Post a Comment