八皇后問題遞歸實現(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);
}

發佈了28 篇原創文章 · 獲贊 6 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章