1 public class PrintMatrixSpiralOrder { 2 public static void printEdge(int[][] m,int tR,int tC,int dR,int dC){ 3 if(tR == dR) 4 { 5 for(int i = tC;i <= dC;i++) 6 { 7 System.out.print(m[tR][i] + " "); 8 } 9 }else if(tC == dC){ 10 for(int i = tR;i <= dR;i++) 11 { 12 System.out.print(m[i][tC] + " "); 13 } 14 }else{ 15 int curC = tC; 16 int curR = tR; 17 while(curC != dC){ 18 System.out.print(m[tR][curC++] + " "); 19 } 20 while(curR != dR){ 21 System.out.print(m[curR++][dC] + " "); 22 } 23 while (curC != tC){ 24 System.out.print(m[dR][curC--] + " "); 25 } 26 while (curR != tR){ 27 System.out.print(m[curR--][tC] + " "); 28 } 29 } 30 } 31 32 public static void printSpiral(int[][] matrix){ 33 int tR = 0; 34 int tC = 0; 35 int dR = matrix.length - 1; 36 int dC = matrix[0].length - 1; 37 // System.out.print(dR); 38 // System.out.print(dC); 39 while( tR <= dR && tC <= dC ){ 40 printEdge(matrix,tR++,tC++,dR--,dC--); 41 } 42 } 43 44 } 45