八皇后的递归实现,运行程序后,平台只能显示少部分解,在此,为了方便解集合的查看,将解集保存在了“F:/result.txt”文件中。
实现代码如下:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
#define N 8
#define SOLU_SIZE 100
struct Solutions{
bool solution[N][N];
};
Solutions solutions[SOLU_SIZE];
int solu_id = 0;
bool isRowOk(int row, int col, bool queen[][N]){
for(int i = 0; i < col; i++){
if(queen[row][i])
return false;
}
return true;
}
bool isColumnOk(int row, int col, bool queen[][N]){
for(int i = 0; i < row; i++){
if(queen[i][col])
return false;
}
return true;
}
bool isLeftCatercornerOk(int row, int col, bool queen[][N]){
int i = row - 1;
int j = col - 1;
while(i >= 0 && j >= 0){
if(queen[i][j])
return false;
else{
i--;
j--;
}
}
return true;
}
bool isRightCatercornerOk(int row, int col, bool queen[][N]){
int i = row - 1;
int j = col + 1;
while(i >= 0 && j < N){
if(queen[i][j])
return false;
else{
i--;
j++;
}
}
return true;
}
bool isOk(int row, int col, bool queen[][N]){
if(isRowOk(row, col, queen)&&
isColumnOk(row, col,queen)&&
isLeftCatercornerOk(row,col,queen)&&
isRightCatercornerOk(row,col,queen))
return true;
else return false;
}
void Print(bool queen[][N]){
for(int i = 0; i < N; i++){
for(int j = 0; j < N; j++){
cout<<queen[i][j]<<" ";
}
cout<<endl;
}
cout<<endl;
}
void PutSolution(bool queen[][N], Solutions solu[], int id) {
for(int i = 0; i < N; i++){
for(int j = 0; j < N; j++){
solu[id].solution[i][j] = queen[i][j];
}
}
}
void Trail(int i, int n, bool queen[][N]){
if(i >= n){
// Print(queen);
PutSolution(queen,solutions,solu_id);
solu_id++;
}else{
for(int j = 0; j < n; j++){
queen[i][j] = 1;
if(isOk(i,j,queen)){
//Print(queen);
Trail(i+1,n,queen);
}
//Print(queen);
queen[i][j] = 0;
}
}
}
void PrintSolutions(Solutions solu[]){
for(int i = 0; i < solu_id; i++){
cout<<"第"<<i+1<<"组解:"<<endl;
for(int j = 0; j < N; j++){
for(int k = 0; k < N; k++){
cout<<solu[i].solution[j][k]<<" ";
}
cout<<endl;
}
cout<<endl;
}
}
void PutSolutionIntoFile(string fileName, Solutions solu[]){
ofstream ofs(fileName.c_str());
for(int i = 0; i < solu_id; i++){
ofs<<"第"<<i+1<<"组解:"<<endl;
for(int j = 0; j < N; j++){
for(int k = 0; k < N; k++){
ofs<<solu[i].solution[j][k]<<" ";
}
ofs<<endl;
}
ofs<<endl;
}
}
void main(){
bool queen[N][N];
for(int i = 0; i < N; i++){
for(int j = 0; j < N; j++){
queen[i][j] = 0;
}
}
//Print(queen);
Trail(0,N,queen);
PrintSolutions(solutions);
PutSolutionIntoFile("F:/result.txt", solutions);
}