您的位置:首页 > 编程语言 > C语言/C++

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

2009-12-07 14:58 337 查看
八皇后的递归实现,运行程序后,平台只能显示少部分解,在此,为了方便解集合的查看,将解集保存在了“F:/result.txt”文件中。

实现代码如下:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

#define N 8
#define SOLU_SIZE 100
struct Solutions{
bool solution

;
};

Solutions solutions[SOLU_SIZE];
int solu_id = 0;

bool isRowOk(int row, int col, bool queen[]
){
for(int i = 0; i < col; i++){
if(queen[row][i])
return false;
}
return true;
}

bool isColumnOk(int row, int col, bool queen[]
){
for(int i = 0; i < row; i++){
if(queen[i][col])
return false;
}
return true;
}

bool isLeftCatercornerOk(int row, int col, bool queen[]
){
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[]
){
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[]
){
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[]
){
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[]
, 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[]
){
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

;
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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: