β Anti clockwise(Contest)
Anti clockwise easy Time Limit: 2 sec Memory Limit: 128000 kB
Problem Statement :
Given an N*N matrix. Print the elements of the matrix in anticlockwise order (see the sample for better understanding). Input First line contains N. N lines follow each containing N space seperated integers.
Constraints:- 2 <= N <= 500 1 <= Mat[i][j] <= 1000 Output Output N*N integers in a single line separated by spaces, which are the elements of the matrix in anti-clockwise order.
Example Sample Input 4 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
Sample output 1 5 9 13 14 15 16 12 8 4 3 2 6 10 11 7
Explanation: We start from 1 , go down till 13 and then go right till 16 then go up till 4 , then we go left till 2 then down and so on in anti-clockwise fashion .
Sample Input 3 1 2 3 4 5 6 7 8 9
Sample output 1 4 7 8 9 6 3 2 5
link: https://my.newtonschool.co/playground/code/hm54i3ux09bk/
import java.io.*; // for handling input/output
import java.util.*; // contains Collections framework
// don't change the name of this class
// you can add inner classes if needed
class Main {
public static void main (String[] args) {
Scanner sc = new Scanner (System.in);
int n = sc.nextInt();
int arr[][] = new int[n][n];
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
arr[i][j] = sc.nextInt();
}
}
// Your code here
int i=0;
int startrow = 0;
int startcol = 0;
while(startrow < n && startcol < n){
for(i=startrow; i<n; i++){
System.out.print(arr[i][startcol] + " ");
}
startcol++;
for(i=startcol; i<n; i++){
System.out.print(arr[n-1][i]+" ");
}
int m=n;
m--;
if(startrow<m){
for(i=m-1; i>=startrow; i--){
System.out.print(arr[i][n-1] + " ");
}
n--;
}
if(startcol<n){
for(i=n-1; i>=startcol; i--){
System.out.print(arr[startrow][i] + " ");
}
startrow++;
}
//System.out.print(arr[1][2]);
//return;
}
//System.out.print(arr[1][2]);
}
}
Last updated