bool rightPlace(int X[],int place,int n)//第place列皇后的位置是否安全
{
if (place ==1)
return true;
if ( X[place] > n || place > n)
return false;
for(int i = 1; i < place; i++)
{
if(X[i] == X[place] || abs(place-i) == abs(X[i]-X[place]) )
return false;
}
return true;
}
void nEmpress(int X[],int n)//N后问题的解 X[I]=K表示第i列的皇后将处于k行
{
int i;
for(i = 1; i <= n; i++)
X[i] = 1;//解向量
int empressth = 1;
do{
if ( rightPlace(X,empressth) )
empressth++;
else
{
X[empressth]++;//换到下一个位置
if(X[empressth] > n) //此列所有的位位置均已遍历完
{
X[empressth] = 1;//此列的皇后位置加到初始化
empressth--; //回溯到上一列皇后
if(empressth < 1) //第一个皇后
break;
X[empressth]++; //求下一个合适位置(前面已遍历)
}
}
}while(empressth <= n);
}