N queens problem

Problem: Place N chess queens on an N*N chessboard so that they cannot attack each other. How many ways are there?

The problem is very simple, but it is difficult for people to think through it, and now I will take you to calculate the result in a concise and effective way.

problem analysis:

--N queens cannot attack each other, that is to say, there can only be one queen on each line, and other lines are not allowed to have queens with the same column and the same slash;

The essence of the problem:

Thinking about this problem carefully, we will find that the possible positions of the queen in the kth row will be determined by the queens in the first k-1 rows, so we consider using a loop to traverse all possible positions of the queens in each row. But here comes the problem, we don't know how much to give to the queen, so we don't know how many recycles are needed, so do we have a solution? Of course there is, we can use recursion, and recursion can solve the problem of unknown loop.

Question Skills:

According to the nature of the problem, we need to determine the recursive termination condition of the problem and how to infer the unknown k-th row from the known k-1 rows. In a solution, how do we judge that it is a positive solution? First, we must be sure that the solution must contain all queens; second, all queens cannot attack each other. With these two constraints, we can easily determine the termination condition of the recursion: when all queens are placed, the recursion ends. Then we will consider how to deduce the kth row if the queens in the first k-1 rows are known to be correctly placed (that is, not attacking each other). After the current k-1 rows are placed, it is very easy for us to determine the kth row: just consider that the placement position of the kth row does not conflict with the previous k-1 rows (it seems like I didn't say it, but it is true So), that is to say, if we use a one-dimensional array quen[N] with N elements to store the queen, the value of each element of the array is the position of the queen represented by the table below, then each element The range of values ​​is (0, N-1). When we want to see whether the queen of row k conflicts with the first k-1 rows, we only need to compare whether the value of the element with k as the subscript is equal to the value of the element with ki(i<k) as the subscript (the same column) or Whether quen[ki] (quen[k+i]) is equal to i (slanted) is enough.

Problem solution:

See the example code column "N Queen -- Full Code"

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325139136&siteId=291194637