Eight queens problem study notes

Online course link

 I saw that the online class is a lazy cat teacher - C language - recursive function - eight queens problem (search, backtracking)

upper diagonal

 The so-called upper diagonal refers to n-col (row number minus column number), but when we use it again for convenience, we usually use (n-col+7), which are all positive numbers; as shown  below
 :
upper diagonal
There are 15 slashes in total;
 therefore, we need 15 bool variables to represent the state of each diagonal
bool d1[14];, each bool value represents a diagonal, and which value is false represents which line cannot place a queen

lower diagonal

 The so-called lower diagonal refers to n+col (row number + column number), as shown in the figure below:

lower diagonal
 there are 15 such slashes;
 therefore, we need 15 bool variables to represent the state of each diagonal line
bool d2[14];, each The bool value represents a diagonal line, which value is false represents which line cannot place the queen

program ideas

Alt

Complete C++ code

#include<iostream>
using namespace std;

/*8皇后问题*/
void gernerate(int num);

//四个公用变量数据初始化 
int place[8];	//第n行皇后所占位置的行号
bool flag[8] = {
    
    1,1,1,1 ,1,1,1,1};	//col列上是否可以放皇后 ,可以放置是真,不可以是假 
bool d1[14]={
    
    1,1,1,1, 1,1,1,1, 1,1,1,1, 1,1};	//(n,col)所在上对角线上是否可以放置皇后?
bool d2[14]={
    
    1,1,1,1, 1,1,1,1, 1,1,1,1, 1,1};	//(n,col)所在下对角线上是否可以放置皇后?
int number=0;		//how many answers does the progrem have


int main(){
    
    
	gernerate(0);
	cout<<number<<endl;
	return 0;
}

void gernerate(int n){
    
    //num is the line of queen
	for(int col=0;col<8;col++) {
    
    
		if(flag[col]&&d1[n-col+7]&&d2[n+col]){
    
    
			place[n]=col;		//放置皇后 
			
			//占领col列及上下对角线 
			flag[col]=false;	
			d1[n-col+7]=false;
			d2[n+col]=false;
			
			/*如果n小于7,那么对下一行进行递归
				否则(n=7),那就是找到了一种方式来摆放
				所以number++; 
			*/
			if(n<7)
				gernerate(n+1);
			else 
				number++;
			
			//释放col列及上下对角线 
			flag[col]=true;
			d1[n-col+7]=true;
			d2[n+col]=true;
		}
	}
}

Guess you like

Origin blog.csdn.net/Stanford_sun/article/details/123266703