fork download
  1. /**
  2.  * Print Matrix in spiral order
  3.  * @author PRATEEK
  4.  */
  5.  
  6. class PrintSpiralMatrix {
  7.  
  8. /**
  9. * Spiral order printing
  10. * @param matrix
  11. */
  12. public static void printSpiral(int[][] matrix)
  13. {
  14. int rowSize = matrix.length ;
  15. int colSize = matrix[0].length;
  16.  
  17. int row=0,col=0,i,j,k;
  18.  
  19. while(row < rowSize && col < colSize)
  20. {
  21. i=col;
  22. for(;i<colSize-col;i++)
  23. System.out.print(matrix[row][i]+" ");
  24.  
  25.  
  26. i=row + 1;
  27. for(;i<rowSize-row;i++)
  28. System.out.print(matrix[i][colSize -col-1]+" ");
  29.  
  30.  
  31. i=(colSize-1-col)-1;
  32. for(;i>=col;i--)
  33. System.out.print(matrix[rowSize -row-1][i]+" ");
  34.  
  35. i=(rowSize-1-row)-1;
  36. for(;i>row;i--)
  37. System.out.print(matrix[i][col]+" ");
  38.  
  39. row++;
  40. col++;
  41. }
  42. }
  43.  
  44. public static void main(String[] args) {
  45. int[][] matrix = {
  46. {1, 2, 3, 4},
  47. {5, 6, 7, 8},
  48. {9, 10, 11, 12},
  49. {13, 14, 15, 16},
  50. {17, 18, 19, 20},
  51. };
  52. printSpiral(matrix);
  53. }
  54. }
  55.  
Success #stdin #stdout 0.07s 380224KB
stdin
Standard input is empty
stdout
1  2  3  4  8  12  16  20  19  18  17  13  9  5  6  7  11  15  14  10