N-Queen

https://www.acmicpc.net/problem/9663

  • ํ•œ ํ–‰์— ํ€ธ์ด ๊ผญ ํ•˜๋‚˜์”ฉ ์žˆ์–ด์•ผ ํ•จ

  • ํ€ธ์„ ๋†“๋Š” ํ•œ ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ 1์ฐจ์› ๋ฐฐ์—ด๋กœ ๋†“์•„์„œ ์ธ๋ฑ์Šค๊ฐ€ ํ–‰์„ ๋œปํ•˜๊ณ , ํ•ด๋‹น ์ˆซ์ž๋Š” ์–ด๋Š ์—ด์— ๋†“์„ ๊ฒƒ์ธ์ง€๊ฐ€ ๋œ๋‹ค.

  • ๋‹ค์Œ ํ–‰์˜ ํ€ธ์„ ์ •ํ•  ๋•Œ๋งˆ๋‹ค ์ด๋ฏธ ๊ฐ™์€ ์—ด์— ์žˆ๋Š”์ง€ ๊ฒ€ํ† ํ•˜๊ณ , ๊ธฐ์กด์˜ ๊ฒƒ๋“ค๊ณผ ๋Œ€๊ฐ์„  ์œ„์น˜์— ๋งž๋Š”์ง€ ๊ฒ€ํ† ํ•˜๋ฉด์„œ ๋งž์„ ๋•Œ๋งŒ ์ง‘์–ด๋„ฃ๊ณ  ๋‹ค์Œ ํ–‰์„ ํ–ฅํ•ด ์žฌ๊ท€

  • ๋ชจ๋“  ํ–‰์ด ์ฐผ๋‹ค๋ฉด, return

  • ์ฒด์ŠคํŒ์˜ ๋Œ€์นญ์„ฑ์„ ๊ณ ๋ คํ•ด ์—ฐ์‚ฐํšŸ์ˆ˜ ์ค„์—ฌ์คŒ

def recu(na):
    global cnt

    if len(na) == n:
        cnt += 1
        return

    for i in range(n):
        if i not in na:
            p = True

            for j in range(len(na)):
                if abs(na[j] - i) == abs(j - len(na)):
                    p = False
                    break

            if p:
                ta = []
                for j in range(len(na)):
                    ta.append(na[j])
                ta.append(i)
                recu(ta)


import sys
sys.stdin = open('note.txt', 'r')

n = int(input())

cnt = 0

# ์ง์ˆ˜
if not n % 2:
    for i in range(n//2):
        a = [i]
        recu(a)
    print(2*cnt)

# ํ™€์ˆ˜
else:
    for i in range(n//2):
        a = [i]
        recu(a)
    cnt *= 2

    a = [n // 2]
    recu(a)
    print(cnt)

Last updated