[Gold IV] Title: N-Queen, Time: 20676 ms, Memory: 36384 KB -BaekjoonHub

This commit is contained in:
SSUM
2026-03-30 20:01:35 +09:00
parent 0cab3f7160
commit 454663cd85
2 changed files with 22 additions and 30 deletions

View File

@@ -1,37 +1,29 @@
import sys
from collections import defaultdict, deque
from heapq import heapify, heappush, heappop
sys.setrecursionlimit(10**6)
input = sys.stdin.readline
n = int(input().strip())
colUsed = [False] * (n)
diagUsed = [False] * ((2*n)-1)
AntidiagUsed = [False] * ((2*n)-1)
N = int(input())
tot = 0
def placeQueens(row):
global tot
cols = [False] * N
diag1 = [False] * (2*N-1)
diag2 = [False] * (2*N-1)
if (row == n):
def Backtrack(Length):
global tot
if (Length == N):
tot += 1
return
for col in range(n):
diagIndex = row - col + n - 1
AntiDiagIndex = row + col
for i in range(N):
if not cols[i] and not diag1[i+Length] and not diag2[i-Length+N-1]:
cols[i] = diag1[i+Length] = diag2[i-Length+N-1] = True
Backtrack(Length+1)
cols[i] = diag1[i+Length] = diag2[i-Length+N-1] = False
if not colUsed[col] and not diagUsed[diagIndex] and not AntidiagUsed[AntiDiagIndex]:
colUsed[col] = True
diagUsed[diagIndex] = True
AntidiagUsed[AntiDiagIndex] = True
placeQueens(row + 1)
colUsed[col] = False
diagUsed[diagIndex] = False
AntidiagUsed[AntiDiagIndex] = False
placeQueens(0)
Backtrack(0)
print(tot)

View File

@@ -4,15 +4,15 @@
### 성능 요약
메모리: 32412 KB, 시간: 29720 ms
메모리: 36384 KB, 시간: 20676 ms
### 분류
백트래킹, 브루트포스 알고리즘
브루트포스 알고리즘, 백트래킹
### 제출 일자
2025년 3월 11일 14:02:42
2026년 3월 30일 20:01:03
### 문제 설명