Thursday, April 24, 2014

[LeetCode] Rotate Image

Problem Statement (link):
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:
This is a problem from CrackCode150 book, it's problem 1.6.

Basically, we modified the values layer by layer from outside to inside. The outer loop is to traverse from outer layer to inner layer, the inner loop is to traverse the pixel entries in each layer.

Code:
class Solution {
public:
    // 4-way swaps from outer to inner
    void rotate(vector<vector<int> > &matrix) {
        int n=matrix.size();
        if (n==0) return;

        // i - layers
        for (int i=0; i<n/2; i++) {
            int st=i, ed=n-i-1;

            // traverse each edge
            for (int j=st; j<ed; j++) {
                int tmp=matrix[st][j];

                // left to top
                matrix[st][j]=matrix[st+ed-j][st];
                // bottom to left
                matrix[st+ed-j][st]=matrix[ed][st+ed-j];
                // right to bottom
                matrix[ed][st+ed-j]=matrix[j][ed];
                // top to right
                matrix[j][ed]=tmp;
            }
        }
    }
};

No comments:

Post a Comment