天天看點

遞歸八皇後問題回溯

//八皇後的回溯遞歸法
#include <stdio.h>
#include <iostream>
#include <math.h>
using namespace std;
int count=0,n;//count為記錄排列的所有可能的情況數量 
int P[11];//P[]記錄當列數為數組下标數時所對應的行數 
int hashtable[11]={false};//注意這種定義方法,将該數組中所有項都定義為false 
void generateP(int index)
{ 
	if(index==n+1)
	{
		count++;
		return;
	}//遞歸邊界 
	for(int x=1;x<=n;x++)//x為行數 
	{
		if(hashtable[x]==false)//hashhtable[]為false表示該行沒有放過棋子 
		{
			bool flag=true;
			for(int pre=1;pre<index;pre++)//周遊已放過棋子的前幾列 
			{
				if(abs(index-pre)==abs(x-P[pre]))//如果該列放的棋子與前幾列放的棋子在同一對角線,沖突 
				{
					flag=false;
					break;
				}
			}
			if(flag)
			{
				P[index]=x;//記錄index列放的棋子為x行 
				hashtable[x]=true;//記錄x行已放過棋子 
				generateP(index+1);
				hashtable[x]=false;
			}
		}
	}
}
int main()
{
	int ans;
	cin >> n;
	generateP(1);
	cout << count;
 }