๋ฌธ์
https://www.acmicpc.net/problem/9663
ํ์ด
# ๋ฐฑ์ค 9663๋ฒ ๋ฌธ์ - N-Queen
import sys
input = sys.stdin.readline
n = int(input().rstrip())
answer = 0
row = [0] * n
def is_promising(x):
for i in range(x):
if row[x] == row[i] or abs(row[x]-row[i]) == abs(x-i):
return False
return True
def n_queens(x):
global answer
if x == n:
answer += 1
else:
for i in range(n):
row[x] = i
if is_promising(x):
n_queens(x+1)
n_queens(0)
print(answer)
์ด ๋ฐฉ์์ผ๋ก ํ๋ฉด ์๊ฐ์ด๊ณผ๊ฐ ๋ฐ์ํด์ pypy3๋ก ์ ์ถํด์ผ ํ๋ค.
๊ทธ๋์ visited๋ฅผ ๋ง๋ค์ด์ ์ ์ถํ๋๋ฐ๋ ์๊ฐ์ด๊ณผ์ด๋ค..
import sys
input = sys.stdin.readline
def check(x):
for i in range(x):
if rows[x] == rows[i] or abs(rows[x] - rows[i]) == x - i:
return False
return True
def dfs(x):
global cnt
if x == n:
cnt += 1
return
for i in range(n):
if visited[i]:
continue
rows[x] = i
if check(x):
visited[i] = True
dfs(x+1)
visited[i] = False
n = int(input())
rows = [0] * n
visited = [False] * n
cnt = 0
dfs(0)
print(cnt)
๋ฐฑํธ๋ํน ๋ฌธ์ ๋ ์ฒ์์ด์ด์ ์ดํดํ๋๋ฐ ๋๋ฌด ์ด๋ ค์ด ๋ฌธ์ ์๋ค.
'๐๏ธ Algorithm > ๐ฉ ๋ฐฑ์ค' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
๐ฉ [๋ฐฑ์ค] [Python] [Gold3] 2206๋ฒ_๋ฒฝ ๋ถ์๊ณ ์ด๋ํ๊ธฐ (0) | 2023.04.17 |
---|---|
๐ฉ [๋ฐฑ์ค] [Python] [Gold4] 1753๋ฒ_์ต๋จ๊ฒฝ๋ก (0) | 2023.04.16 |
๐ฉ [๋ฐฑ์ค] [Python] [Gold4] 5052๋ฒ_์ ํ๋ฒํธ ๋ชฉ๋ก (0) | 2023.04.14 |
๐ฉ [๋ฐฑ์ค] [Python] [Silver4] 1302๋ฒ_๋ฒ ์คํธ์ ๋ฌ (0) | 2023.04.12 |
๐ฉ [๋ฐฑ์ค] [Python] [Gold4] 4179๋ฒ_๋ถ! (0) | 2023.04.11 |