fork download
  1. // Java program to print a given matrix in spiral form
  2. import java.io.*;
  3.  
  4. class GFG {
  5. // Function print matrix in spiral form
  6. static void spiralPrint(int m, int n, int a[][])
  7. {
  8. int i, k = 0, l = 0;
  9. /* k - starting row index
  10. m - ending row index
  11. l - starting column index
  12. n - ending column index
  13. i - iterator
  14. */
  15.  
  16. while (k < m && l < n) {
  17. // Print the first row from the remaining rows
  18. for (i = l; i < n; ++i) {
  19. System.out.print(a[k][i] + " ");
  20. }
  21. k++;
  22.  
  23. // Print the last column from the remaining columns
  24. for (i = k; i < m; ++i) {
  25. System.out.print(a[i][n - 1] + " ");
  26. }
  27. n--;
  28.  
  29. // Print the last row from the remaining rows */
  30. if (k < m) {
  31. for (i = n - 1; i >= l; --i) {
  32. System.out.print(a[m - 1][i] + " ");
  33. }
  34. m--;
  35. }
  36.  
  37. // Print the first column from the remaining columns */
  38. if (l < n) {
  39. for (i = m - 1; i >= k; --i) {
  40. System.out.print(a[i][l] + " ");
  41. }
  42. l++;
  43. }
  44. }
  45. }
  46.  
  47. // driver program
  48. public static void main(String[] args)
  49. {
  50. int R = 3;
  51. int C = 6;
  52. int a[][] = { { 1, 2, 3, 4, 5, 6 },
  53. { 7, 8, 9, 10, 11, 12 },
  54. { 13, 14, 15, 16, 17, 18 } };
  55. spiralPrint(R, C, a);
  56. }
  57. }
Success #stdin #stdout 0.04s 2184192KB
stdin
Standard input is empty
stdout
1 2 3 4 5 6 12 18 17 16 15 14 13 7 8 9 10 11