Talk about n queen

Place n queens on an n * n chessboard, requiring the same row and the same column. Two slashes cannot be placed.
This is a simple backtracking problem.
But how to judge whether it can be released is difficult.


At that time, I thought about opening a two-dimensional array to judge whether this coordinate can be put.
But there is a problem here. The slashes of two queens (1 and 2) may have focus. Then we will reset this coordinate when we backtrack (backtrack from queen 2). But in this case the slash of queen 1 has no effect.


The queen is placed from the 0th row and there can only be one queen in a row, so the i-th queen is also the i-th row.
Use an array flag to represent. flag[i]=jThis indicates that the queen in row i is placed in column j.
In this way, when considering the diagonal line, you can use the slope of the two-point straight line (Y1-Y2 / X1-X2).

#include<iostream>
#include<set>
#include<vector> 
using namespace std;
int ans=0;
int flag[100];//flag[i]=j, 第i个皇后的列数j 
bool place(int col,int row){
	for(int i=0;i<row;i++){ //找出已经放置的queen的行,判断他们与将要放的queen是否冲突
		if(flag[i]==col||abs(i-row)==abs(col-flag[i])) return false;
	}
	return true;
}
void dfs(int n,int row){
	if(row==n){
		ans++;
		return;
	}
	for(int i=0;i<n;i++){//列数	
		if(place(i,row)){//判断第row行,第i列可不可以放queen
			flag[row]=i;
			dfs(n,row+1);
			//flag[row]=0;
			//发现去掉这里也没事,原因:我们先判断再放,所以回溯也没事。
		}
	}	
}
int main(void){
	int n=4;
	dfs(n,0);
	cout<<ans;
}
Published 161 original articles · Like 68 · Visitors 20,000+

Guess you like

Origin blog.csdn.net/qq_43179428/article/details/105340933