八皇后问题,经典的回溯。
不需要定义一个board[8][8],定义一个一维数组locate[8]即可。
#include <iostream>
using namespace std;
int locate[8];
int total_count=0;
void print_board(){
int i, j;
for (i=0; i<8; i++){
cout<<endl;
for (j=0; j<8; j++) {
if (locate[i]==j){
cout<<"@";
}
else{
cout<<".";
}
}
}
}
bool find(int k, int m) //check the place the kth queen in kth row, mth column
{
bool result = true;
for (int i=0; i<k; i++) { //choose the previous rows
if ((locate[i]==m) || (abs(locate[i]-m)==abs(k-i))){
// cout<<"bad i,k,m="<<i<<" "<<k<<" "<<m<<endl;
result = false;
break;
}
}
return result;
}
void place(int k){ //place the kth queen in kth row
int i;
if (k==8){
total_count++;
cout<<endl;
for (int i=0; i<8; i++) //choose i as the column
cout<<locate[i]<<" ";
cout<<endl;
print_board();
cout<<endl<<endl<<endl;
return;
}
for (i=0; i<8; i++){ //tentatively try the column from 1 to 7
if (find(k,i)) {
locate[k]=i;
place(k+1);
}
}
}
int main()
{
int i;
//initialize
for (i=0; i<8; i++)
locate[i]=-1;
place(0);
cout<<endl;
cout<<"total_count="<<total_count<<endl;
return 0;
}
这个回溯算法最经典,但不是效率最高的。下次再写几个效率高的。