leetcode

题目链接
Description
You are given an n x n 2D matrix representing an image.

Rotate the image by 90 degrees (clockwise).

Note:

You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.

Example 1:

Given input matrix =
[
[1,2,3],
[4,5,6],
[7,8,9]
],

rotate the input matrix in-place such that it becomes:
[
[7,4,1],
[8,5,2],
[9,6,3]
]

解题思路
题目要求在原矩阵位置上对矩阵进行90度旋转。矩阵旋转可以看做是由外到内按层旋转,需要操作的层数是矩阵大小的一半。经过观察可以看出,每个位置的旋转只与四个位置有关,可以看做是四个位置的替换。
举例:对一个5*5的矩阵来说,位置[0,1]的旋转,n=matrix.size()-1=4
[0,1]->[3,0], [3,0]->[4,3], [4,3]->[1,4], [1,4]->[0,1] 即:
[i,j]->[n-j,i], [n-j,i]->[n-i,n-j], [n-i,n-j]->[j,n-i], [j,n-i]->[i,j]

示例代码

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