八皇后问题递归实现(C++)

八皇后的递归实现,运行程序后,平台只能显示少部分解,在此,为了方便解集合的查看,将解集保存在了“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);
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值