求N皇后问题

The right solution is in bottom: 

Input a number in range 0~9: 
6
The steps for the problem  of queen are as follows: 
The solution scheme is:   2  6  3  1  4  5        
The solution scheme is:   3  6  4  2  5  4        
The solution scheme is:   4  6  3  5  2  3        
The solution scheme is:   5  3  6  4  2  2   

The codes with bugs:

//find the solution for N queen problem
# include <iostream>
# include <iomanip>
using namespace std;
void queen(int i, int n, int q[]);
bool place(int i, int j, int q[]);
void display(int q[], int n);
int main()
{
	cout << "Input a number in range 0~9: " << endl;
	int n = 0;
	cin >> n;
	int *q;
	q = new int[n+1];
	cout << "The steps for the proble of queen are as follows: " << endl;
	for (int k = 1; k <= n; ++k){
		for (int i = 0; i <= n; i++) {
			q[i] = -1;
		}
		q[1] = k;
		queen(2, n, q);
		if(q[n] != -1){
			cout << "The solution scheme is: ";
			display(q, n);
		}
	}
	return 0;
}
void queen(int i, int n, int q[])
{
	if (i > n){
		return;
	}else{
		for (int j = 1; j <= n; j++) {
			if (place(i, j, q)){
				q[i] = j;
				queen(i+1, n, q);
			}
		}
	}
}
bool place(int i, int j, int q[])
{
	for (int k = 1; k < i; k++) {
		if (j == q[k] || abs(j-q[k]) == abs(i - k)) {
			return false;
		}
	}
	return true;
}
void display(int q[], int n)
{
	for (int i =1; i <= n; i++) {
		cout << setw(3) << q[i];
	}
	cout << endl;
}

The right outputs:

Input a number range from 2 to 10.
6
The solution steps are as follows:
The solution is: 2 4 6 1 3 5
The solution is: 3 6 2 5 1 4
The solution is: 4 1 5 2 6 3
The solution is: 5 3 1 6 4 2

The corresponding codes:

# include <iostream>
# include <iomanip>
using namespace std;
const int MAX = 10;
int q[MAX];
void queen(int i, int n);
void display(int n);
bool place(int i, int j);
int main()
{
	cout << "Input a number range from 2 to 10." << endl;
	int n;
	cin >> n;
	cout << "The solution steps are as follows:"<< endl;
	for (int i = 0; i <= n; i++){
		q[i] = -1;
	}
	for (int k = 1; k <= n; k++){
		q[1] = k;
		queen(2, n);
	}
	return 0;
}
void queen(int i, int n)
{
	if (i > n){
		display(n);
	}else{
		for (int j = 1; j <= n; j++){
			if (place(i, j)){
				q[i] = j;
				queen(i+1, n);
			}
		}
	}
}
bool place(int i, int j)
{
	for (int k = 1; k < i; k++) {
		if ((q[k] == j)|| (abs(q[k] - j) == abs(i - k))){
			return false;
		}
	}
	return true;
}
void display(int n)
{
	cout << "The solution is:" ;
	for (int i = 1; i <= n; i++) {
		cout << setw(2) << q[i] ;
	}
	cout << endl;
}

猜你喜欢

转载自blog.csdn.net/weixin_38396940/article/details/121217599