LeetCode 48. Rotate Image [Medium]

旋转正方形矩阵。

题目来源:https://leetcode.com/problems/rotate-image

题目难度:Medium

解答1[Java]:

核心思想

旋转的数字旋转之后,几个位置的数字之间是有规律的。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public void rotate(int[][] matrix) {
int r1 = 0;
int c1 = 0;
int r2 = matrix.length - 1;
int c2 = matrix[0].length - 1;
while (r1 < r2) {
rotateEdge(matrix, r1++, c1++, r2--, c2--);
}
}

public static void rotateEdge(int[][] m, int r1, int c1, int r2, int c2) {
int times = c2 - c1;
int tmp = 0;
for (int i = 0; i != times; i++) {
tmp = m[r1][c1 + i];
m[r1][c1 + i] = m[r2 - i][c1];
m[r2 - i][c1] = m[r2][c2 - i];
m[r2][c2 - i] = m[r1 + i][c2];
m[r1 + i][c2] = tmp;
}
}
}