ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค [lv4] N-Queen ํŒŒ์ด์ฌ

2021. 5. 16. 00:49ใ†๐Ÿ”ฑ Algorithm/Else

๋ฌธ์ œ ์„ค๋ช…

๊ฐ€๋กœ, ์„ธ๋กœ ๊ธธ์ด๊ฐ€ n์ธ ์ •์‚ฌ๊ฐํ˜•์œผ๋กœ๋œ ์ฒด์ŠคํŒ์ด ์žˆ์Šต๋‹ˆ๋‹ค. ์ฒด์ŠคํŒ ์œ„์˜ n๊ฐœ์˜ ํ€ธ์ด ์„œ๋กœ๋ฅผ ๊ณต๊ฒฉํ•  ์ˆ˜ ์—†๋„๋ก ๋ฐฐ์น˜ํ•˜๊ณ  ์‹ถ์Šต๋‹ˆ๋‹ค.

์˜ˆ๋ฅผ ๋“ค์–ด์„œ n์ด 4์ธ๊ฒฝ์šฐ ๋‹ค์Œ๊ณผ ๊ฐ™์ด ํ€ธ์„ ๋ฐฐ์น˜ํ•˜๋ฉด n๊ฐœ์˜ ํ€ธ์€ ์„œ๋กœ๋ฅผ ํ•œ๋ฒˆ์— ๊ณต๊ฒฉ ํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.

์ฒด์ŠคํŒ์˜ ๊ฐ€๋กœ ์„ธ๋กœ์˜ ์„ธ๋กœ์˜ ๊ธธ์ด n์ด ๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ์ฃผ์–ด์งˆ ๋•Œ, n๊ฐœ์˜ ํ€ธ์ด ์กฐ๊ฑด์— ๋งŒ์กฑ ํ•˜๋„๋ก ๋ฐฐ์น˜ํ•  ์ˆ˜ ์žˆ๋Š” ๋ฐฉ๋ฒ•์˜ ์ˆ˜๋ฅผ returnํ•˜๋Š” solutionํ•จ์ˆ˜๋ฅผ ์™„์„ฑํ•ด์ฃผ์„ธ์š”.

 

์ œํ•œ์‚ฌํ•ญ

  • ํ€ธ(Queen)์€ ๊ฐ€๋กœ, ์„ธ๋กœ, ๋Œ€๊ฐ์„ ์œผ๋กœ ์ด๋™ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
  • n์€ 12์ดํ•˜์˜ ์ž์—ฐ์ˆ˜ ์ž…๋‹ˆ๋‹ค.

์ž…์ถœ๋ ฅ ์˜ˆ

n result
4 2

 


์ ‘๊ทผ

- N-Queen์€ ์œ ์ผํ•œ ๋ฐฑํŠธ๋ž˜ํ‚น ๋ฌธ์ œ์— ํ•ด๋‹น

- ๋ชจ๋“  ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ count ํ•˜๋ฉด์„œ, ํ•„์š”์—†๋Š” ๋ถ€๋ถ„์„ ๊ฐ€์ง€์น˜๊ธฐํ•œ๋‹ค.

- ๋ฐฑํŠธ๋ž˜ํ‚น์€ n์ด ์ž‘์„ ๋•Œ(๋ฌธ์ œ์กฐ๊ฑด: n <= 12) or ์–ด์ฉ” ์ˆ˜ ์—†์ด ๋ชจ๋“  ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ ๊ตฌํ•ด์•ผ ํ•  ๋•Œ ์‚ฌ์šฉํ•œ๋‹ค.

=> ๋ฐฑํŠธ๋ž˜ํ‚น์€ ์žฌ๊ท€ ๊ตฌ์กฐ๋ฅผ ์‚ฌ์šฉํ•œ๋‹ค.

 

๊ตฌํ•˜๊ณ ์ž ํ•˜๋Š” ๊ฒƒ

- ์กฐ๊ฑด์„ ๋งŒ์กฑํ•˜๋Š” ๊ฒฝ์šฐ์˜ ์ˆ˜  !=  ์กฐ๊ฑด์„ ๋งŒ์กฑํ•˜๋Š” ์ฒด์ŠคํŒ์˜ ํ˜•ํƒœ

- ์กฐ๊ฑด์„ ๋งŒ์กฑํ•˜๋Š” ์ฒด์ŠคํŒ์˜ ํ˜•ํƒœ๊ฐ€ ์–ด๋–ค ๋ชจ์Šต์ธ์ง€ ๊ตฌํ•  ํ•„์š”๊ฐ€ ์—†๋‹ค ==> ์กฐ๊ฑด์„ ๋งŒ์กฑํ•˜๋Š” ๊ฒฝ์šฐ์˜ ์ˆ˜๋งŒ ์นด์šดํŠธํ•˜์—ฌ return

 

ํ’€์ด ์ฝ”๋“œ

 


def solution(n: int):
    return search([0] * n, 0)


def search(queen: list, row: int):
    n = len(queen)
    count = 0

    if n == row:
        return 1

    for col in range(n):
        queen[row] = col
        if check(queen, row):
            count += search(queen, row + 1)
    return count


def check(queen: list, row: int):
    for i in range(row):
        if queen[i] == queen[row] or abs(queen[i] - queen[row]) == row - i:
            return False

    return True

 

 

 

 

search() ํ•จ์ˆ˜: ์žฌ๊ท€ ๊ตฌ์กฐ๋กœ ์ž‘์„ฑ

์ธ์ž: ๊ฐ row์— ํ•ด๋‹น๋˜๋Š” queen ๋ณ€์ˆ˜: list ,  ๊ฐ row์˜ ๋ฒˆํ˜ธ (0, 1, 2 ... n )

# ์žฌ๊ท€ ํ•จ์ˆ˜ => ํƒˆ์ถœ๊ตฌ๊ฐ€ ์žˆ์–ด์•ผํ•œ๋‹ค. (if n == row)
def search(queen, row):
    n = len(queen)
    count = 0

    if n == row:
        return 1

    for col in range(n):
        queen[row] = col  # row, col ์˜์—ญ์— ํ€ธ์„ ๋ฐฐ์น˜
        if check(queen, row):
            count += search(queen, row + 1)  # ๋‹ค์Œ ์—ด๋กœ ํ€ธ์„ ๋„˜๊ธด๋‹ค.
    return count  # ๋ฐฐ์น˜ํ•  ์ˆ˜ ์žˆ๋Š” ๋ฐฉ๋ฒ•์˜ ์ˆ˜ ๋ฆฌํ„ด

 

check() ํ•จ์ˆ˜

def check(queen, row):
    for i in range(row):
        if queen[i] == queen[row] or abs(queen[i] - queen[row]) == row - i:
            return False
    return True

์œ„ ๊ทธ๋ฆผ์—์„œ ๋ณด๋“ฏ, row - i ์™€ queen[row] - queen[i] ์˜ ๊ฐ’์ด ๊ฐ™๋‹ค๋Š” ๊ฒƒ์€ ๋™์ผ ๋Œ€๊ฐ์„  ์ƒ์— ์žˆ์Œ์„ ๋œปํ•œ๋‹ค.

queen[i] == queen[row] ๊ฐ€ ๋œปํ•˜๋Š” ๋ฐ”๋Š”, ํ•˜๋‚˜์˜ ํ–‰์—์„œ ๊ฐ™์€ ์—ด์— ์œ„์น˜ํ•จ์„ ์˜๋ฏธ.

 

์ฆ‰ ์œ„์˜ ๋‘ ์กฐ๊ฑด ์ค‘ ํ•˜๋‚œ๋ฅผ ๋งŒ์กฑํ•˜๋ฉด false๋ฅผ return