Monday, October 14, 2013

Rotate Image [Leetcode]

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?

Solution: find the mapping relationship as shown in Fig. 1, and then rotate the matrix layer by layer.

Fig. 1. Mapping Relationship

class Solution {
public:
    void rotate(vector<vector<int> > &matrix) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        int n = matrix.size();
        if(n<=1)    return;
        for(int i=0; i<n/2; ++i)
            for(int j=i; j<n-1-i; ++j){
                int t = matrix[i][j];
                //left to top
                matrix[i][j] = matrix[n-1-j][i];
                //bottom to left
                matrix[n-1-j][i] = matrix[n-1-i][n-1-j];
                //right to bottom
                matrix[n-1-i][n-1-j] = matrix[j][n-1-i];
                //top to right
                matrix[j][n-1-i] = t;
            }
    }
};

No comments:

Post a Comment