이 문제는 d2 난이도였지만 조금 생각하기 어려웠다.
일단 round라는 변수를 두고 한 round당 세 번 턴을 한다.
한 round가 지나면 사각형 겉의 한 줄이 채워지기 때문에 채울때 0과 n(사각형의 길이)를 기준으로 턴을 하는 것이 아니라, round-1와 n-round를 기준으로 턴을 하게 된다.
그리고 right, left, up, down 변수를 두어 현재 진행방향을 알려주었고, 턴의 기준이 된다면 진행방향 기준 상태를 바꿔 턴을 시킨다.
import sys
sys.stdin = open('input.txt')
T = int(input())
for tc in range(1, T+1):
N = int(input())
m_row = [0] * N
matrix = []
for _ in range(N):
matrix.append(list(m_row))
matrix[0][0] = 1
round = 1
row, col = 0
left, up, down = 0
right = 1
for i in range(2, (N*N)+1):
# 오른쪽으로갈 때
if right and row <= N-round:
row += 1
if row == N-round:
right = 0
down = 1
# 아래로 갈 때
elif down and col <= N-round:
col += 1
if col == N-round:
down = 0
left = 1
# 왼쪽으로 갈 때
elif left and row >= round-1:
row -= 1
if row == round-1:
left = 0
up = 1
round += 1
# 위로 올라갈 때
elif up and col >= round-1:
col -= 1
matrix[col][row] = i
if col == round-1:
up = 0
right = 1
matrix[col][row] = i
print("#{}".format(tc))
for col in range(N):
for row in range(N):
print(matrix[col][row], end=' ')
print()