【题目】
给定一个整型矩阵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 public void cyclePrint(int[][] matrix) 2 { 3 if(matrix == null || matrix.length == 0 || matrix[0].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.length - 1; 12 while(tR <= dR && tC <= dC) // 当子矩阵的左上角坐标在右下角坐标的右方或者下方,则打印过程结束 13 { 14 printEdge(matrix, tR++, tC++, dR--, dC--); 15 } 16 } 17 18 public void printEdge(int[][] m, int tR, int tC, int dR, int dC) 19 { 20 if(tR == dR) // 子矩阵只有一行时 21 { 22 for(int i = tC; i <= dC; i++) 23 { 24 System.out.print(m[tR][i] + " "); 25 } 26 } 27 else if(tC == dC) // 子矩阵只有一列时 28 { 29 for(int i = tR; i <= dR; i++) 30 { 31 System.out.print(m[i][tC] + " "); 32 } 33 } 34 else 35 { 36 int curC = tC; 37 int curR = tR; 38 while(curC != dC) 39 { 40 System.out.print(m[tR][curC] + " "); 41 curC++; 42 } 43 while(curR != dR) 44 { 45 System.out.print(m[curR][dC] + " "); 46 curR++; 47 } 48 while(curC != tC) 49 { 50 System.out.print(m[dR][curC] + " "); 51 curC--; 52 } 53 while(curR != tR) 54 { 55 System.out.print(m[curR][tC] + " "); 56 curR--; 57 } 58 } 59 }
来源:左程云老师《程序员代码面试指南》