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?

 

思路:

先沿着X轴中线翻转,再沿着对角线翻转。

1 2 3 -> 8 9 7 -> 8 4 1

4 5 6 -> 4 5 6 -> 9 5 2

8 9 7 -> 1 2 3 -> 7 6 3

 

Solution:

public void rotate(int[][] matrix) {
    int n = matrix.length;
    for(int i=0; i<n/2; i++) {
        int[] tmp = matrix[i];
        matrix[i] = matrix[n-i-1];
        matrix[n-i-1] = tmp;
    }
    for(int i=0; i<n; i++) {
        for(int j=i; j<n; j++) {
            int tmp = matrix[i][j];
            matrix[i][j] = matrix[j][i];
            matrix[j][i] = tmp;
        }
    }
}

 

C++版本:

void rotate(vector<vector<int>>& matrix) {
    int n = matrix.size();
    for(int i=0; i<n/2; i++) {
        swap(matrix[i], matrix[n-i-1]);
    }
    for(int i=0; i<n; i++) {
        for(int j=i; j<n; j++) {
            swap(matrix[i][j], matrix[j][i]);
        }
    }
}

 

你可能感兴趣的:(LeetCode)