eight queens problem in Python

后端 未结 4 1398
自闭症患者
自闭症患者 2021-02-03 16:34

8-queens problem in Python.

Hi! I only start teaching Python, so could someone explain the code written below (found in the Internet)? Some pieces of the code are compli

4条回答
  •  故里飘歌
    2021-02-03 17:12

    BOARD_SIZE = 8
    
    def under_attack(col, queens): # You do not need to fill in these fields. This is a helper function for the solve function.
        left = right = col
        for r, c in reversed(queens): # Reversing queens causes them to be iterated over in reverse order.
            left, right = left-1, right+1
            if c in (left, col, right):
                return True
        return False
    
    def solve(n):
        if n == 0: return [[]]
        smaller_solutions = solve(n-1) # It appears that in solving this board, it solves all boards smaller than it in a recursive manner.
        return [solution+[(n,i+1)] # This line appears to be in error. Have you run this code and verified that it runs correctly?
            for i in range(BOARD_SIZE)
                for solution in smaller_solutions
                    if not under_attack(i+1, solution)]
    for answer in solve(BOARD_SIZE): print answer
    

提交回复
热议问题