https://leetcode.cn/problems/rotate-image/
👍逐圈遍历
这个还挺符合自己想法的,思路差不多,但是没写出来。 参考答案:https://leetcode.cn/problems/rotate-image/solution/li-kou-48xiao-bai-du-neng-kan-dong-de-fang-fa-zhu-/ 参考了答案后写出来了,这个还是最好理解的,每圈的左上角坐标为
(pos1,pos1)
,右下角坐标为(pos2,pos2)
,然后逐圈遍历。
public void rotate(int[][] matrix) {
int pos1 = 0, pos2 = matrix.length - 1;
while (pos1 < pos2) {
int add = 0;
while (pos1 + add < pos2) {
int temp = matrix[pos1][pos1 + add];
matrix[pos1][pos1 + add] = matrix[pos2 - add][pos1];
matrix[pos2 - add][pos1] = matrix[pos2][pos2 - add];
matrix[pos2][pos2 - add] = matrix[pos1 + add][pos2];
matrix[pos1 + add][pos2] = temp;
add++;
}
pos1++;
pos2--;
}
}
分组旋转
不能借助辅助数组还挺难的,想不到… 参考答案:https://leetcode.cn/problems/rotate-image/solution/48-xuan-zhuan-tu-xiang-fu-zhu-ju-zhen-yu-jobi/
public void rotate(int[][] matrix) {
int n = matrix.length;
for (int i = 0; i < n / 2; i++) {
for (int j = 0; j < (n + 1) / 2; j++) {
int tmp = matrix[i][j];
matrix[i][j] = matrix[n - 1 - j][i];
matrix[n - 1 - j][i] = matrix[n - 1 - i][n - 1 - j];
matrix[n - 1 - i][n - 1 - j] = matrix[j][n - 1 - i];
matrix[j][n - 1 - i] = tmp;
}
}
}
巧解
“对角线反转+逐行反转” 参考答案:https://leetcode.cn/problems/rotate-image/solution/-by-huan-huan-20-8df6/ 太巧妙了,我自己是想不到…😥