Saturday, March 16, 2013

Rotate Image (to add alternative method)

/*
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?
*/
class Solution {
public:
    void rotate(vector<vector<int> > &matrix) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int size = matrix.size();
        if(size==0) return;
        if(matrix[0].size()!=size) return;
        vector<vector<int>> result = matrix;
        for(int i=0; i<size; i++){
           for(int j=0; j<size; j++){
              result[i][j] = matrix[size-1-j][i];
           }
        }
        matrix = result;
        return;
    }
};

No comments:

Post a Comment