给定一个整型矩阵matrix,请按照转圈的方式打印它。
例如: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
打印结果为:1,2,3,4,8,12,16,15,14,13,9, 5,6,7,11, 10
【要求】 额外空间复杂度为O(1)。
1 package my_basic.class_3; 2 3 /*转圈打印矩阵*/ 4 public class Code_05_PrintMatrixSpiralOrder { 5 public static void spiralOrderPrint(int[][] matrix) { 6 int tr = 0; 7 int tc = 0; 8 int dr = matrix.length-1; 9 int dc = matrix[0].length-1; 10 while(tr <= dr && tc <= dc) { 11 printEdge(matrix,tr++,tc++,dr--,dc--); 12 } 13 } 14 15 public static void printEdge(int[][] matrix, int tr, int tc, int dr, int dc) { 16 if (tr == dr) { /*打印一横*/ 17 for (int i = tc; i <= dc ; i++) { 18 System.out.println(matrix[tr][i]); 19 } 20 }else if(tc == dc) { /*打印一列*/ 21 for (int i = tr; i <= dr ; i++) { 22 System.out.println(matrix[i][tc]); 23 } 24 }else { 25 int curC = tc; 26 int curR = tr; 27 28 while (curC != dr) { 29 System.out.print(matrix[tr][curC] + " "); 30 curC++; 31 } 32 while (curR != dc) { 33 System.out.print(matrix[curR][dc] + " "); 34 curR++; 35 } 36 while(curC != tc) { 37 System.out.print(matrix[dr][curC] + " "); 38 curC--; 39 } 40 while(curR != tr) { 41 System.out.print(matrix[curR][tc] + " "); 42 curR--; 43 } 44 45 } 46 } 47 48 public static void main(String[] args) { 49 int[][] matrix = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, 50 { 13, 14, 15, 16 } }; 51 spiralOrderPrint(matrix); 52 } 53 }