Miscellaneous: The Eight Queens Problem of Classic Algorithms

0 Preface

The eight queens problem can be regarded as a classic problem that cannot be more classic in the algorithm problem. Here, here, let's examine the general form of the eight queens problem, that is, the N queens problem.

1. Title description

I believe everyone is clear about the problem description of the eight queens problem. We directly describe the N queens algorithm as follows:

On a sheet of N × NN \times NN×On N 's chessboard, put N chess queens so that they will not eat each other. How many different placement methods are there?

This question is also included on Leetcode, which corresponds to the 51 and 52 questions . The only difference between them is whether they need to print out the complete display.

Without loss of generality, here, we only count the number of placement methods without printing out the specific placement methods.

2. Algorithm analysis

The typical solution to this problem is the depth-first traversal method.

We look at every position on the i-th row. If a queen can be visited in that position, place a queen on it, and then examine the possible placements in the next row, knowing that there is a queen on all rows. After that, we add one to the total number of times.

3. Code implementation

The specific python code is given as follows:

class Solution:
    def totalNQueens(self, n: int) -> int:
        ans = 0
        cache = []
        
        def dfs(i):
            nonlocal ans, cache
            if i >= n:
                ans += 1
                return
            for j in range(n):
                if any(c == j or i-r == abs(c-j) for r, c in cache):
                    continue
                cache.append((i, j))
                dfs(i+1)
                cache.pop()
            return
        
        dfs(0)
        return ans

Guess you like

Origin blog.csdn.net/codename_cys/article/details/111464123