Advertisement
unknown_0711

Untitled

Sep 9th, 2022
22
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.49 KB | None | 0 0
  1. Scanner sc = new Scanner(System.in);
  2. int n = sc.nextInt();
  3. int m = sc.nextInt();
  4.  
  5. int[][] arr = new int[n][m];
  6. for(int i = 0; i < n; i++) {
  7. for(int j = 0; j < m; j++) {
  8. arr[i][j] = sc.nextInt();
  9. }
  10. }
  11.  
  12. int startRow = 0, endRow = n - 1;
  13. int startColumn = 0, endColumn = m - 1;
  14.  
  15.  
  16. int count = 0;
  17.  
  18. while(count < m * n) {
  19. // top row
  20. for(int i = startColumn; i <= endColumn; i++) {
  21. System.out.print(arr[startRow][i] + " ");
  22. count++;
  23. }
  24.  
  25. startRow++;
  26. // printing last column
  27. for(int i = startRow; i <= endRow; i++) {
  28. System.out.print(arr[i][endColumn] + " ");
  29. count++;
  30. }
  31.  
  32. endColumn--;
  33.  
  34. if(startColumn > endColumn) break;
  35. if(startRow > endRow) break;
  36.  
  37. // printing last row
  38. for(int i = endColumn; i >= startColumn; i--) {
  39. System.out.print(arr[endRow][i] + " ");
  40. count++;
  41. }
  42.  
  43. endRow--;
  44.  
  45. if(startColumn > endColumn) break;
  46. if(startRow > endRow) break;
  47.  
  48. // printing first column
  49. for(int i = endRow; i >= startRow; i--) {
  50. System.out.print(arr[i][startColumn] + " ");
  51. count++;
  52. }
  53.  
  54. startColumn++;
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement