Your logic is perfectly alright.There is nothing wrong with the logic, seems fine.
Ac. to me , something wrong with accessing the input or printing the output you can check that yourself as i m not familiar with java.
PS: I took your code and submitted in c++ . Surprisingly it got an AC answer. Have a look. CodeChef: Practical coding for everyone
You can check my code implementation in python. It’s concise and simple to understand.
I=lambda:int(input())
def mainFunction():
testCase=I()
for t in range(testCase):
n=I()
count = 1
for i in range(n):
matRow = ''
if i % 2 == 0:
for j in range(n):
matRow = matRow +str(count)+" "
count=count+1
else:
count = count + n-1
for j in range(n):
matRow = matRow +str(count)+" "
count=count-1
count = count + n+1
print(matRow)
mainFunction()