The Eight Queens Problem (with detailed explanation)

The Eight Queens Problem is a classic backtracking problem. I saw a solution a long time ago and found it difficult to understand. It was completely different from what I thought, and then I kept thinking about it as a very complicated problem, which was also a problem that was delayed for a long time. It's going to end today.
        The problem is the problem of placing pieces on the chessboard. It is necessary to ensure that they cannot attack each other. Therefore, the idea is: Assume that the first piece of the first row of the chessboard is placed, and then judge whether it matches, and if it matches, it can be placed in the second place Place the second pawn in the row, and keep looping like this until all possible situations are met and you can quit. The implementation code is as follows: (I haven't taken an algorithm class, so the language may not be very professional)
 
 
#include<bits/stdc++.h> using namespace std; int que[8],coun=0; /* This que array is the location where it is stored. The clever thing is that the subscript represents the row and the value it represents It is the position of the piece in that row, for example: que[4]=5, which means that the fourth row (starting from row 0) is placed on the fifth square (starting from 0) coun is the counter, representing all possible numbers */ bool is_ok(int row) {//The function to judge whether the position is in line with the non-mutual attack for(int i=0;i<row;i++){ if(que[row]==que[i]| |fabs(que[i]-que[row])==fabs(i-row)) return false; //que[row]==que[i] Determine if there are multiple pieces in the same column//fabs( que[i]-que[row])==fabs(i-row) This is a variant of the formula//Writing in a more understandable form is: //que[i]+i==que[row]+row ;Check whether there are more pieces on the diagonal right//que[i]-i==que[row]-row;Check whether there are more pieces on the diagonal left} return true; } void queen(int row) { if(row= =8){ coun++;//At the end point, add one to the counter, exit return; } for(int i=0;i<8;i++){ que[row]=i;//Put the pieces if(is_ok(row) )//Continue to put down a queen(row+1); } } int main() { queen(0); cout<<coun<<endl; return 0; }

The N queen problem can also be solved, and the placement of the four queen problems can be output. There are only two kinds of problems that can be tried. I feel a sense of achievement~~~

Guess you like

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