n后问题(回溯法)

//
//Description: N后问题(回溯法)
//
#include <iostream>
#include <math.h>
#include <iomanip>
using namespace std;

int n;//皇后个数
int x[100];//当前解
static long sum;//当前已找到的可行方案数


bool place(int k)
{
	for (int j = 1; j<k; j++)
	{
		if ((abs(k - j) == abs(x[j] - x[k])) || (x[j] == x[k]))
			return false;
	}
	return true;
}

void backtrack(int t)
{
	if (t>n)
	{
		sum++;
		cout << " 第 " << setw(2) << sum << "  个可行解:";
		for (int i = 1; i <= n; i++)
		{
			cout << x[i] << "  ";
		}
		cout << endl;
	}
	else
	for (int i = 1; i <= n; i++)
	{
		x[t] = i;
		if (place(t))
			backtrack(t + 1);
	}
}

long nQueen(int nn)
{
	n = nn;
	sum = 0;
	for (int i = 1; i <= n; i++)
	{
		x[i] = 0;
	}
	backtrack(1);
	return sum;
}

void main()
{
	cout << "\n\t===============N后问题(回溯法)=================\n";
	cout << "Please enter the numbers of Queens:" << endl;
	cin >> n;
	nQueen(n);

	cout << "欲在" << n << "×" << n << "的棋盘上放置满足条件的" << n << "个皇后,可以得到解的个数为 " << sum << endl;
}

    原文作者:回溯法
    原文地址: https://blog.csdn.net/aastoneaa/article/details/6762359
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞