Recursive and non-recursive implementation of N Queens

Everyone should know the famous Eight Queens problem, but just in case, let me say it again:

The eight-queen problem is a chess-based problem whose content is to solve how to place eight queens on an 8×8 chess board so that no queen can directly capture the other queens? That is, no two queens can be on the same horizontal, vertical or diagonal line.

And N queens, as the name suggests, is the same rule extended to N queens.

Two methods are given here:

Iterate:

#include <iostream>
#include <cmath>

using namespace std;

const int MAXN = 1005;

int data[MAXN];//Stored procedure data
int count;//for counting

bool check(int K){//Check whether the current point is qualified
	for(int i=1 ; i<K ; i++){
		if(data[i] == data[K] || abs(data[i]-data[K]) == K-i)return false;
	}
	return true;
}

void Queen(int N){
	int K = 1;
	data[K] = 0;
	while(K>0){
		++data[K];
		for(; data[K]<=N ; ++data[K]){
			if(check(K))break;
		}
		if(data[K]<=N){
			if(K == N){//find the solution
				for(int i=1 ; i<=N ; i++)cout<<data[i];
				cout<<endl;
				++count;
			}else {
				++K;
				data[K] = 0;//This point must be updated to 0, remember to remember
			}
		}else {
			--K;
		}
	}
}

int main(){
	
	int N;
	while(cin>>N){
		count = 0;
		Queen(N);
		cout<<count<<endl;	
	}
	
	return 0;
}

Recursion (recommended, easy to understand):

#include <iostream>
#include <cmath>

using namespace std;

const int MAXN = 1005;

int data[MAXN];//Stored procedure data
int count;//for counting

bool check(int K){//Check whether the current point is qualified
	for(int i=1 ; i<K ; i++){
		if(data[i] == data[K] || abs(data[i]-data[K]) == K-i)return false;
	}
	return true;
}

void Queen(int N,int K){
	if(K > N){//find the solution
		for(int i=1 ; i<=N ; i++){
			cout<<data[i];
		}
		cout<<endl;
		++count;
		return;
	}else {
		for(int i=1 ; i<=N ; i++){
			data[K] = i;
			if(check(K))Queen(N,K+1);//If the current point is feasible, start to find the next point
		}
	}
}

int main(){
	
	int N;
	while(cin>>N){
		count = 0;
		Queen(N,1);
		cout<<count<<endl;	
	}
	
	return 0;
}


Guess you like

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