递归---n皇后

时间:2022-06-29 13:08:19

---恢复内容开始---

#include "stdafx.h"
#include <iostream>
#include <fstream> //文件流
#include <iomanip>
#include <cstdlib> using namespace std;
void queenSolve(int rowCurrent, int n, int *&queenlist, int &count, ofstream &os);
void Print(int n, int *&queenlist, ofstream &os);
bool Check(int rowCurrent, int *&queelist); int main()
{
int n;
cout << "请输入规模n: " << endl;
cin >> n;
if (n<)
{
cerr << "问题规模必须大于4" << endl;
return ;
} int *queenlist = new int[n];
int count = ;
ofstream os;
os.open("result.txt");
queenSolve(,n, queenlist, count, os);
cout << "共有" << count << "种解法" << endl;
os.close(); system("pause");
return ;
}
void Print(int n, int *&queenlist, ofstream &os){
for (int i = ; i < n; i++)
{
for (int j = ; j < n; j++){
os <<(queenlist[i] == j ? : );
os << setw(); //设置域宽为n个字符,<iomanip>
}
os << "\n";
}
os << "\n";
}
bool Check(int rowCurrent, int *&queelist){
for (int i = ; i < rowCurrent; i++){
if (queelist[rowCurrent] == queelist[i])
return false;
if (abs(rowCurrent - i) == abs(queelist[rowCurrent] - queelist[i])) //<cstdlib>
return false;
}
return true;
}
void queenSolve(int rowCurrent, int n, int *&queenlist, int &count, ofstream &os)
{
if (rowCurrent == n)
{
++count;
os << "第" << count << "个解" << endl;
Print(n,queenlist,os);
}
else{
for (int i = ; i < n; i++)
{
queenlist[rowCurrent] = i;
if (Check(rowCurrent, queenlist))
queenSolve(rowCurrent+, n, queenlist, count, os);
}
}
}

---恢复内容结束---