Friday, May 2, 2014

LeetCode: 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?


We can do this in place by rotate four elements each time. For example, if the matrix is 2*2, the transformation will be

00 01 => 10 00
10 11 => 11 01
If the matrix is 3*3, the transformation will be
00 01 02 20 01 00 20 10 00
10 11 12 => 10 11 12 => 10 11 01
20 21 22 20 21 02 22 12 02

C++ Code:

/*
 * func: rotate_image
 * goal: rotate the n*n image 90 degree clockwise
 * @param matrix: image matrix
 * return:
 */
void rotate(vector<vector<int> > &matrix){
    size_t n = matrix.size();
    for(size_t i=0; i < n/2; ++i){
        for(size_t j=0; j<n-1-i; ++j){
            auto tmp = matrix[i][j];
            matrix[i][j] = matrix[n-1-j][i];
            matrix[n-1-j][i] = matrix[n-1-i][n-1-j];
            matrix[n-1-i][n-1-j] = matrix[j][n-1-i];
            matrix[j][n-1-i] = tmp;
        }
    }
}

Python Code:

# func: rotate a image by 90 degree clockwise
# @param matrix: input image matrix
# @return: rotated image
def rotate_image(matrix):
    size = len(matrix)
    for i in xrange(size/2):
        for j in xrange(i, size-1-i):
            tmp = matrix[i][j]
            matrix[i][j] = matrix[size-1-j][i]
            matrix[size-1-j][i] = matrix[size-1-i][size-1-j]
            matrix[size-1-i][size-1-j] = matrix[j][size-1-i]
            matrix[j][size-1-i] = tmp

    return matrix

No comments:

Post a Comment