백트래킹
문제col[j] == col[i]
를 통해 현재 열보다 위에 있는 열의 행과 겹치는 지 검사abs(col[i] - col[j]) == (i - j)
(행의 차) 와 (열의 차)가 같으면 대각선에 있는 것이므로 이를 검사## C의 알고리즘을 그대로 따라했지만 시간초과가 발생했다..
def promising(i):
for j in range(i):
if col[j] == col[i] or abs(col[i] - col[j]) == (i-j):
return False
return True
def N_queen(i):
global result
if i == n:
result += 1
else:
for j in range(n):
col[i] = j
if promising(i):
N_queen(i+1)
n = int(input())
col = [0 for _ in range(n)]
result = 0
N_queen(0)
print(result)
시간초과
가 발생한다.이 그림 처럼 대각선의 조건식을 설정할 수 있다..
n, ans = int(input()), 0
a, b, c = [False]*n, [False]*(2*n-1), [False]*(2*n-1)
def solve(i):
global ans
if i == n:
ans += 1
return
for j in range(n):
if not (a[j] or b[i+j] or c[i-j+n-1]):
a[j] = b[i+j] = c[i-j+n-1] = True
solve(i+1)
a[j] = b[i+j] = c[i-j+n-1] = False
solve(0)
print(ans)
행의 차
와 열의 차
가 같을 때로 구분할 수 있다.rebas 블로그