解题思路

这道题目其实更像是找规律的,找到规律后,可以使用旋转一圈的方式来实现,如图:
image.png

代码

  1. var rotate = function(matrix) {
  2. let len = matrix.length;
  3. for (let i = 0; i < len / 2; i++){
  4. for (let j = i; j < len - i - 1; j++) {
  5. let temp = matrix[i][j];
  6. let m = len - j - 1;
  7. let n = len - i - 1;
  8. matrix[i][j] = matrix[m][i];
  9. matrix[m][i] = matrix[n][m];
  10. matrix[n][m] = matrix[j][n];
  11. matrix[j][n] = temp;
  12. }
  13. }
  14. return matrix;
  15. };
  16. const matrix = [[1,2,3],[4,5,6],[7,8,9]]
  17. // matrix = [[1,2,3],[4,5,6],[7,8,9]]
  18. // 输出:[[7,4,1],[8,5,2],[9,6,3]]
  19. // matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]
  20. // 输出:[[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]
  21. console.log(rotate(matrix));