正方形矩阵 顺时针旋转90度

 1 package my_basic.class_3;
 2 
 3 /*正方形矩阵 顺时针旋转矩阵 90度*/
 4 public class Code_06_RotateMatrix {
 5     
 6     public static void rotate(int[][] matrix) {
 7         int tr = 0;
 8         int tc = 0;
 9         int dr = matrix.length-1;
10         int dc = matrix[0].length-1;
11         while(tr < dr) {
12             rotateEdge(matrix,tr++,tc++,dr--,dc--); /*从外圈  到里圈*/
13         }
14     }
15 
16     public static void rotateEdge(int[][] matrix, int tr, int tc, int dr, int dc) {
17         int times = dc - tc; 
18         int tmp = 0;
19         for(int i=0; i!=times;i++) {
20             tmp = matrix[tr][tc+i];
21             matrix[tr][tc + i] = matrix[dr-i][tc];
22             matrix[dr-i][tc] = matrix[dr][dc-i];
23             matrix[dr][dc-i] = matrix[tr+i][dc];
24             matrix[tr+i][dc] = tmp;
25         }
26     }
27     public static void printMatrix(int[][] matrix) {
28         for (int i = 0; i < matrix.length; i++) {
29             for(int j = 0; j < matrix[0].length;j++) {
30                 System.out.print(matrix[i][j] + " ");
31             }
32             System.out.println();
33         }
34     }
35     
36     public static void main(String[] args) {
37         int[][] matrix = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 },
38                 { 13, 14, 15, 16 } };
39         printMatrix(matrix);
40         System.out.println("===============");
41         rotate(matrix);
42         printMatrix(matrix);
43     }
44 }

 

上一篇:剑指offer 19. 画图让抽象形象化 顺时针打印矩阵


下一篇:test