Link to problem: https://www.codechef.com/JUNE20B/problems/EVENM
Iam trying to solve a simple problem challenge, but getting TLE.
I had a different approach earlier, so tried this, again with no success.
I know this can be optimized further but can't figure how.
The problem: Print the matrix in a format depending upon the input.
If input is divisible by 2 then in this format:
else in this format:
Time limit: 1 sec
nxn matrix, where 1<=n<=1000
My code:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int cases = Integer.parseInt(br.readLine());
for(int i = 0; i < cases; i++) {
int n = Integer.parseInt(br.readLine());
if(n%2==1) {
int cur = 0;
for(int j = 1; j <= n; j++) {
for(int k = 1; k <= n; k++) {
System.out.print(++cur);
if(k!=n) System.out.print(" ");
}
System.out.println();
}
}
else {
int first = 0;
boolean b = true;
for(int j = 1; j <= n; j++) {
for(int k = 1; k <= n; k++) {
if(b) System.out.print(++first);
else System.out.print(first--);
if(k!=n) System.out.print(" ");
}
if(b)b = false;
else b = true;
first+=n;
System.out.println();
}
}
}
According to the judge, this is taking slightly more than 2 seconds, which is double the time expected, so this is totally un-optimized