题意:

image.png

解题思路:

  1. 思路:两次交换
  2. 1. 上下交换 00 => 20, 01 => 21, 02 => 22
  3. 2. 右斜线交换 00 => 00, 01 => 10, 02 => 20

PHP代码实现:

  1. class Solution {
  2. function rotate(&$matrix) {
  3. $m = count($matrix);
  4. $n = count($matrix[0]);
  5. //上下交换. 00=>20, 01 => 21, 02 => 22
  6. for ($i = 0; $i < floor($m / 2); $i ++) {
  7. for ($j = 0; $j < $n; $j++) {
  8. $temp = $matrix[$i][$j];
  9. $matrix[$i][$j] = $matrix[$m - $i - 1][$j];
  10. $matrix[$m - $i - 1][$j] = $temp;
  11. }
  12. }
  13. //右斜线交换. 00=>00, 01 => 10, 02 => 20
  14. for ($i = 0; $i < $m; $i++) {
  15. for ($j = $i; $j < $n; $j++) {
  16. $temp = $matrix[$i][$j];
  17. $matrix[$i][$j] = $matrix[$j][$i];
  18. $matrix[$j][$i] = $temp;
  19. }
  20. }
  21. }
  22. }

GO代码实现:

  1. func rotate(matrix [][]int) {
  2. m := len(matrix)
  3. n := len(matrix[0])
  4. for i := 0; i < m / 2; i++ {
  5. for j := 0; j < n; j++ {
  6. matrix[i][j], matrix[m - i - 1][j] = matrix[m - i - 1][j], matrix[i][j]
  7. }
  8. }
  9. for i := 0; i < m; i++ {
  10. for j := i; j < n; j++ {
  11. matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
  12. }
  13. }
  14. }