image.png

解决思路

image.png

  1. public void rotate(int[][] matrix) {
  2. int n = matrix.length;
  3. // 转置矩阵
  4. for (int i = 0; i < n; i++) {
  5. for (int j = i; j < n; j++) {
  6. int tmp = matrix[j][i];
  7. matrix[j][i] = matrix[i][j];
  8. matrix[i][j] = tmp;
  9. }
  10. }
  11. //每一行进行反转
  12. // reverse each row
  13. for (int i = 0; i < n; i++) {
  14. for (int j = 0; j < n / 2; j++) {
  15. int tmp = matrix[i][j];
  16. matrix[i][j] = matrix[i][n - j - 1];
  17. matrix[i][n - j - 1] = tmp;
  18. }
  19. }
  20. }