public class test27 { public static void spiralOrderPrint(int[][] matrix){ //左上角点行和列 int tR = 0; int tC = 0; //右下角点行和列 int dR = matrix.length-1; int dC = matrix[0].length -1; //左上方点往右下移动,右下方点往左上移动 while (tR <= dR && tC <= dC){ printEdge(matrix , tR++ , tC++ , dR-- , dC--);//每次 } } public static void printEdge(int[][] m ,int a , int b ,int c ,int d) { //a行b列左上角点的位置,c行d列右下角点的位置 if(a == c){//只剩一条横线,打印横线 for(int i = b ; i <= d ; i++){ System.out.println(m[a][i] + " "); } }else if(b ==d){//只剩一列竖线,打印竖线 for(int i = a ; i <= c ; i++){ System.out.println(m[i][b] + " "); } }else{ int curC = b; int curR = a; while (curC != d){ System.out.println(m[a][curC] +" "); curC++; } while (curR != c){ System.out.println(m[curR][d] +" "); curR++; } while (curC != b){ System.out.println(m[c][curC] +" "); curC--; } while (curR != a){ System.out.println(m[curR][b] +" "); curR--; } } } }
转圈打印矩阵
最新推荐文章于 2024-11-15 18:38:47 发布