"Coding Interview Guide" -- 将正方形矩阵顺时针转动90°

题目

  给定一个N×N矩阵matrix,把这个矩阵调整成顺时针转动90°后的形式

  例如, 1    2    3    4

      5    6    7    8

                  9    10  11  12

     13  14  15  16

  顺时针转动90°后为:

        13   9   5  1

     14  10  6  2

     15  11  7  3

     16  12  8  4

要求

  时间复杂度为O(1)

 

 1     public void rotate(int[][] matrix)
 2     {
 3         if(matrix == null || matrix.length != matrix[0].length || matrix.length == 0)
 4         {
 5             return;
 6         }
 7 
 8         int tR = 0;
 9         int tC = 0;
10         int dR = matrix.length - 1;
11         int dC = matrix[0].length - 1;
12         while(tR < dR)
13         {
14             rotateEdge(matrix, tR++, tC++, dR--, dC--);  // 矩阵可以由左上角坐标及矩阵长和宽共同表示,或者由左上角坐标和右下角坐标联合表示
15         }
16     }
17 
18     public void rotateEdge(int[][] m, int tR, int tC, int dR, int dC)
19     {
20         int times = dC - tC;
21         int temp = 0;
22         for(int i = 0; i < times; i++)
23         {
24             temp = m[tR][tC + i];
25             m[tR][tC + i] = m[dR - i][tC];
26             m[dR - i][tC] = m[dR][dC - i];
27             m[dR][dC - i] = m[tR + i][dC];
28             m[tR + i][dC] = temp;
29         }
30     }

 

 

来源:左程云老师《程序员代码面试指南》

posted @ 2019-06-08 20:47  Latuper  阅读(216)  评论(0编辑  收藏  举报