2n queen problem (classic 8 queen problem)

The 8 queen problem is a classic case of backtracking algorithms. Backtracking is also called deep search, which is simply a recursive enumeration.
The backtracking algorithm is better than exhaustive methods in that once the goal is not reached or is not optimal, it will immediately go back up to reselect and find another path.
It's a bit like a brute force cracking, but once the goal is not reached, the current solution will not continue, so it saves a lot of computation than brute force cracking.

Problem description
  Given an n*n chessboard, there are some positions on the board that cannot be placed with queens. Now we need to put n black queens and n white queens into the chessboard, so that any two black queens are not in the same row, column or diagonal, and any two white queens are not in the same row, The same column or the same diagonal. How many ways are there in total? n is less than or equal to 8.
Input format
  The first line of input is an integer n, which represents the size of the chessboard.
  In the next n lines, there are n integers of 0 or 1 in each line. If an integer is 1, it means that the corresponding position can be a queen. If an integer is 0, it means that the corresponding position cannot be a queen.
Output format
  outputs an integer, indicating how many ways there are in total.
Sample input
. 4
1 1 1 1
1 1 1 1
. 1. 1. 1 1``
1111
sample output
2
embodied reference others add a little program content, as follows:

while True:
    try:  # 先放白皇后,再放黑皇后
        n = int(input())  # n是一开始的黑白皇后的个数
        s = []  # 存放原始的0,1位置
        result = []
        temp_W = [None for x in range(n)]  # 临时存放白皇后
        temp_B = [None for x in range(n)]  # 临时存放黑皇后
        for i in range(n):
            s.append(input().split())  # 输入0,1位置
        def valid_W(temp_W, row):  # 判断当前位置放白皇后是否合法
            if s[row][temp_W[row]] == "1":
                for i in range(row):
                    # 下面这个判断条件是:判断对角线,判断是否是白皇后自己的列
                    if abs(temp_W[i] - temp_W[row]) == abs(i - row) or temp_W[i] == temp_W[row]:
                        return False
                return True

        def valid_B(temp_B,row,temp_W):  # 判断当前位置放黑皇后是否合法
            if s[row][temp_B[row]] == '1' and temp_B[row] != temp_W[row]:  # 判断这个位置能否放皇后
                for i in range(row):
                    # 判断是否对角线,是否是自己的列,判断这个位置有没有先放白皇后
                    if abs(temp_B[i] - temp_B[row]) == abs(i-row) or temp_B[i] == temp_B[row]:
                        return False
                return True

        def dfs_W(temp_W,row):  # temp记录当前所有合法的皇后的位置,row是继续往下一行里面放皇后
            if row == n:  # 当前进行到n,表示找到了白皇后的一种排列方式,跳出递归
                dfs_B(temp_B,0)  # 白皇后排好之后跳到排列黑皇后
            else:
                for col in range(n):  # col是列,就是要遍历这一行的所有列,判断在某个位置上是否合法
                    temp_W[row] = col
                    if valid_W(temp_W,row):
                        dfs_W(temp_W,row+1)

        def dfs_B(temp_B,row):  # temp记录当前所以合法皇后的位置,row是继续往下一行里面放皇后
            if row == n:  # 当前进行到n,表示找到了n皇后的一种排列方式,跳出递归
                result.append(temp_B[:])  # 将找到的黑皇后排列方式存储到result里面
                return
            else:
                for col in range(n):  # col是列,遍历这一行所有列,判断在某位置是否合法
                    temp_B[row] = col
                    if valid_B(temp_B,row,temp_W):
                        dfs_B(temp_B,row+1)

        dfs_W(temp_W,0)
        print(len(result))
    except:
        break  # 通过异常输入跳出循环(如不输入直接运行)

Guess you like

Origin blog.csdn.net/qq_45701131/article/details/105718746