eight queens problem in Python

后端 未结 4 1376
自闭症患者
自闭症患者 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 16:55

    Here is my solution. It is much more easier to understand and straighforward:

    def under_attack(row, column, existing_queens):
        if not len(existing_queens): return False
        for queen in existing_queens:
            if not len(queen):
                continue
            r,c = queen
            if r == row: return True # Check row
            if c == column: return True # Check column
            if (column-c) == (row-r): return True # Check left diagonal
            if (column-c) == -(row-r): return True # Check right diagonal
        return False
    
    def iter_solve(n):
        solutions = None
        for row in range(1, n+1):
            # for each row, check all valid column
            solutions = check(solutions, row, n)
        return solutions
    
    def check(solutions, row, n):
        new_solutions = []
        for column in range(1, n+1):
            if not solutions or not len(solutions):
                new_solutions.append([] + [(row, column)])
            else:
                for solution in solutions:
                    if not under_attack(row, column, solution):
                        new_solutions.append(solution + [(row, column)])
        return new_solutions
    

提交回复
热议问题