✔ 풀이를 위한 아이디어
✔ 정답 코드 (개선 전)
N = int(input())
chess = [[0]*N for _ in range(N)]
vertical = [0]*N
count = 0
def backTracking(chess, current):
if current == N:
global count
count += 1
for i in range(N):
if not vertical[i] and not look(chess, i, current):
chess[current][i] = 1
vertical[i] = 1
backTracking(chess, current + 1)
chess[current][i] = 0
vertical[i] = 0
def look(chess, x, y):
exist = 0
_x = x
while y >= 0:
if _x >= 0:
if chess[y][_x]:
exist = 1
if x < N:
if chess[y][x]:
exist = 1
_x -= 1
x += 1
y -= 1
return exist
current = 0
backTracking(chess, current)
print(count)
✔ 정답 코드 (개선 후)
N = int(input())
chess = [[0]*N for _ in range(N)]
vertical = [1]*N
bevel = [1]*(2*N-1)
r_bevel = [1]*(2*N-1)
count = 0
def backTracking(chess, current):
if current == N:
global count
count += 1
for i in range(N):
if vertical[i] and bevel[i+current] and r_bevel[(N-i-1)+current]:
chess[current][i] = 1
vertical[i] = 0
bevel[i+current] = 0
r_bevel[(N-i-1)+current] = 0
backTracking(chess, current + 1)
chess[current][i] = 0
vertical[i] = 1
bevel[i+current] = 1
r_bevel[(N-i-1)+current] = 1
current = 0
backTracking(chess, current)
print(count)