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?

描述

给出一个 n*n 的整数型数组,要求将其顺时针旋转 90°,要求不能使用额外数组辅助

分析

将一张纸上下翻转,然后按照对角线翻转,即相当于这张纸旋转 90°

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class Solution {
public void rotate(int[][] matrix) {

int n = matrix.length;

for (int i = 0; i < n / 2; i++) { // 上下翻转
for (int j = 0; j < n; j++) {
int t = matrix[i][j];
matrix[i][j] = matrix[n - 1 - i][j];
matrix[n - 1 - i][j] = t;
}
}

for (int i = 0; i < n; i++) { // 对角线翻转
for (int j = i + 1; j < n; j++) {
int t = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = t;
}
}
}
}