문제 조건 :
N = 3
1 2 3
8 9 4
7 6 5
N = 4
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
[제약사항]
data를 생성함.data의 [0][0]은 1로 넣고, cnt = 1, index = N을 생성함.cnt: 채운 칸의 숫자를 의미 N: 현재 진행중인 껍질의 N을 의미data[row][col]메모리: 52,352 KB, 시간: 57 ms, 코드길이: 844 Bytes
T = int(input())
answer = []
for num in range(1, T+1):
N = int(input())
data = [[0]* N for _ in range(N)]
row, col = 0, 0
data[row][col] = 1
cnt = 1
index = N
def print_matrix(matrix):
for row in matrix:
print(" ".join(f"{x}" for x in row))
for i in range(2, N ** 2 + 1):
if cnt == (4*index - 4):
index -= 2
cnt = 0
if cnt <= index - 1:
cnt += 1
col += 1
elif index <= cnt <= 2*index - 2:
cnt += 1
row += 1
elif 2*index - 1 <= cnt <= 3*index - 3:
cnt += 1
col -= 1
elif 3*index - 2 <= cnt <= 4*index - 5:
cnt += 1
row -= 1
data[row][col] = i
answer.append(f"#{num}")
for row in data:
answer.append(" ".join(f"{x}" for x in row))
print("\n".join(answer))
맞음.
N = 3
matrix = [[0] * N for _ in range(N)]
dx = [0, 1, 0, -1] # 행 이동 (→ ↓ ← ↑)
dy = [1, 0, -1, 0] # 열 이동
x, y, dir = 0, 0, 0 # 시작 위치, 방향
for num in range(1, N * N + 1):
matrix[x][y] = num
nx, ny = x + dx[dir], y + dy[dir]
if 0 <= nx < N and 0 <= ny < N and matrix[nx][ny] == 0:
x, y = nx, ny
else:
dir = (dir + 1) % 4 # 방향 전환
x, y = x + dx[dir], y + dy[dir]