Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Scanner sc = new Scanner(System.in);
- int n = sc.nextInt();
- int m = sc.nextInt();
- int[][] arr = new int[n][m];
- for(int i = 0; i < n; i++) {
- for(int j = 0; j < m; j++) {
- arr[i][j] = sc.nextInt();
- }
- }
- int startRow = 0, endRow = n - 1;
- int startColumn = 0, endColumn = m - 1;
- int count = 0;
- while(count < m * n) {
- // top row
- for(int i = startColumn; i <= endColumn; i++) {
- System.out.print(arr[startRow][i] + " ");
- count++;
- }
- startRow++;
- // printing last column
- for(int i = startRow; i <= endRow; i++) {
- System.out.print(arr[i][endColumn] + " ");
- count++;
- }
- endColumn--;
- if(startColumn > endColumn) break;
- if(startRow > endRow) break;
- // printing last row
- for(int i = endColumn; i >= startColumn; i--) {
- System.out.print(arr[endRow][i] + " ");
- count++;
- }
- endRow--;
- if(startColumn > endColumn) break;
- if(startRow > endRow) break;
- // printing first column
- for(int i = endRow; i >= startRow; i--) {
- System.out.print(arr[i][startColumn] + " ");
- count++;
- }
- startColumn++;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement