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),然后逐圈遍历。

  1. public void rotate(int[][] matrix) {
  2. int pos1 = 0, pos2 = matrix.length - 1;
  3. while (pos1 < pos2) {
  4. int add = 0;
  5. while (pos1 + add < pos2) {
  6. int temp = matrix[pos1][pos1 + add];
  7. matrix[pos1][pos1 + add] = matrix[pos2 - add][pos1];
  8. matrix[pos2 - add][pos1] = matrix[pos2][pos2 - add];
  9. matrix[pos2][pos2 - add] = matrix[pos1 + add][pos2];
  10. matrix[pos1 + add][pos2] = temp;
  11. add++;
  12. }
  13. pos1++;
  14. pos2--;
  15. }
  16. }

分组旋转

不能借助辅助数组还挺难的,想不到… 参考答案:https://leetcode.cn/problems/rotate-image/solution/48-xuan-zhuan-tu-xiang-fu-zhu-ju-zhen-yu-jobi/

  1. public void rotate(int[][] matrix) {
  2. int n = matrix.length;
  3. for (int i = 0; i < n / 2; i++) {
  4. for (int j = 0; j < (n + 1) / 2; j++) {
  5. int tmp = matrix[i][j];
  6. matrix[i][j] = matrix[n - 1 - j][i];
  7. matrix[n - 1 - j][i] = matrix[n - 1 - i][n - 1 - j];
  8. matrix[n - 1 - i][n - 1 - j] = matrix[j][n - 1 - i];
  9. matrix[j][n - 1 - i] = tmp;
  10. }
  11. }
  12. }

巧解

“对角线反转+逐行反转” 参考答案:https://leetcode.cn/problems/rotate-image/solution/-by-huan-huan-20-8df6/ 太巧妙了,我自己是想不到…😥