# 分析

matrix.size() 为奇数时，位置的对应关系相同，但左上角区域并不是整个矩阵的四分之一，如下图示：

1. s w a p ( m a t r i x [ i ] [ j ] , m a t r i x [ j ] [ n − i − 1 ] ) ; swap(matrix[i][j], matrix[j][n-i-1]); swap(matrix[i][j],matrix[j][n−i−1]);
2. s w a p ( m a t r i x [ i ] [ j ] , m a t r i x [ n − i − 1 ] [ n − j − 1 ] ) ; swap(matrix[i][j], matrix[n-i-1][n-j-1]); swap(matrix[i][j],matrix[n−i−1][n−j−1]);
3. s w a p ( m a t r i x [ i ] [ j ] , m a t r i x [ n − j − 1 ] [ i ] ) ; swap(matrix[i][j], matrix[n-j-1][i]); swap(matrix[i][j],matrix[n−j−1][i]);

``````class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
int n = matrix.size();
if(n == 0) { return; }
int r = (n>>1)-1; //左上角区域的最大行下标，
int c = (n-1)>>1; //左上角区域的最大列下标，行列下标从 0 开始。
for(int i = r; i >= 0; --i) {
for(int j = c; j >= 0; --j) {
swap(matrix[i][j], matrix[j][n-i-1]);
swap(matrix[i][j], matrix[n-i-1][n-j-1]);
swap(matrix[i][j], matrix[n-j-1][i]);
}
}
}
};

java实现

``````import java.util.Arrays;

public class Solution {

// 4 个数轮换，大风车转呀转悠悠

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

public static void main(String[] args) {
int[][] matrix = {
{5, 1, 9, 11},
{2, 4, 8, 10},
{13, 3, 6, 7},
{15, 14, 12, 16}
};

Solution solution = new Solution();
solution.rotate(matrix);

for (int[] row : matrix) {
System.out.println(Arrays.toString(row));
}
}
}

## 方法二：利用翻转代替旋转

``````class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
int n = matrix.size();
// 水平翻转
for (int i = 0; i < n / 2; ++i) {
for (int j = 0; j < n; ++j) {
swap(matrix[i][j], matrix[n - i - 1][j]);
}
}
// 主对角线翻转
for (int i = 0; i < n; ++i) {
for (int j = 0; j < i; ++j) {
swap(matrix[i][j], matrix[j][i]);
}
}
}
};

`````` 5  1  9 11
2  4  8 10
13  3  6  7
15 14 12 16

`````` 5  1  9 11                 15 14 12 16
2  4  8 10                 13  3  6  7
------------   =水平翻转=>   ------------
13  3  6  7                  2  4  8 10
15 14 12 16                  5  1  9 11

``````15 14 12 16                   15 13  2  5
13  3  6  7   =主对角线翻转=>   14  3  4  1
2  4  8 10                   12  6  8  9
5  1  9 11                   16  7 10 11

java实现

``````class Solution {
public void rotate(int[][] matrix) {
int n = matrix.length;
// 先以对角线（左上-右下）为轴进行翻转
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
int tmp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = tmp;
}
}
// 再对每一行以中点进行翻转
int mid = n >> 1;
for (int i = 0; i < n; i++) {
for (int j = 0; j < mid; j++) {
int tmp = matrix[i][j];
matrix[i][j] = matrix[i][n - 1 - j];
matrix[i][n - 1 - j] = tmp;
}
}
}
}

j++) {
int tmp = matrix[i][j];
matrix[i][j] = matrix[i][n - 1 - j];
matrix[i][n - 1 - j] = tmp;
}
}
}
}

``复制代码``