#include <cstdlib>
#include <iostream>
#include <string>
#include <iterator>
#include <vector>
#include <algorithm>
#include <fstream>
#include <functional>
#include <sstream>
using namespace std;
//输出一个序列
template<typename Iter>
void print(Iter first,Iter last,
const char* nm = "",
const char* sep = "/t",
ostream& os = cout)
{
if(nm != 0 && *nm != '/0')
os << nm << ": " << sep;
typedef typename iterator_traits<Iter>::value_type VT;
copy(first,last,ostream_iterator<VT >(os,sep));
os << endl;
}
//八皇后算法
void eightQueen()
{
short num = 0;
ofstream outf("eight_queen.txt"); //结果保存在eight_queen.txt中
short qp[9] = {0}; //qp[1]~qp[8]代表棋盘的8列,qp[i]=j表示第i列第j行放一个皇后
for ( short lie = 1; lie <= 8; ++lie)
{
short hang = 0;
for ( hang = qp[lie]+1; hang <= 8; ++hang)//此处用qp[lie]代替了栈的使用
{
bool isOk = true;
//检查当前列当前行可否放皇后
for (short i = 1; i < lie; ++i)
if ( qp[i] == hang || abs(qp[i]-hang) == abs(i-lie) )
{
isOk = false;
break;
}
if ( isOk )
{//当前位置可用
qp[lie] = hang;
if ( lie == 8 )
{
//如果是最后一列,表示搜索到一种放法,将其输出
ostringstream os;
os << ++num;
print(qp+1,qp+9,os.str().c_str(),"/t",outf);
}
else //否则跳出当前列,进入下一列
break;
}
}
if ( hang == 9 )
{//当前列已经搜索完,回退到上一列
qp[lie] = 0; //将当前列清零,保证下一次搜索该列时从第1行开始
lie -= 2; //for语句还要进行+1操作,减2才是回退1列
}
if ( lie == -1)
break; //第一列已经搜索完毕,算法结束
}
}
int main(int argc, char *argv[])
{
eightQueen();
system("pause");
}
#include <iostream>
#include <string>
#include <iterator>
#include <vector>
#include <algorithm>
#include <fstream>
#include <functional>
#include <sstream>
using namespace std;
//输出一个序列
template<typename Iter>
void print(Iter first,Iter last,
const char* nm = "",
const char* sep = "/t",
ostream& os = cout)
{
if(nm != 0 && *nm != '/0')
os << nm << ": " << sep;
typedef typename iterator_traits<Iter>::value_type VT;
copy(first,last,ostream_iterator<VT >(os,sep));
os << endl;
}
//八皇后算法
void eightQueen()
{
short num = 0;
ofstream outf("eight_queen.txt"); //结果保存在eight_queen.txt中
short qp[9] = {0}; //qp[1]~qp[8]代表棋盘的8列,qp[i]=j表示第i列第j行放一个皇后
for ( short lie = 1; lie <= 8; ++lie)
{
short hang = 0;
for ( hang = qp[lie]+1; hang <= 8; ++hang)//此处用qp[lie]代替了栈的使用
{
bool isOk = true;
//检查当前列当前行可否放皇后
for (short i = 1; i < lie; ++i)
if ( qp[i] == hang || abs(qp[i]-hang) == abs(i-lie) )
{
isOk = false;
break;
}
if ( isOk )
{//当前位置可用
qp[lie] = hang;
if ( lie == 8 )
{
//如果是最后一列,表示搜索到一种放法,将其输出
ostringstream os;
os << ++num;
print(qp+1,qp+9,os.str().c_str(),"/t",outf);
}
else //否则跳出当前列,进入下一列
break;
}
}
if ( hang == 9 )
{//当前列已经搜索完,回退到上一列
qp[lie] = 0; //将当前列清零,保证下一次搜索该列时从第1行开始
lie -= 2; //for语句还要进行+1操作,减2才是回退1列
}
if ( lie == -1)
break; //第一列已经搜索完毕,算法结束
}
}
int main(int argc, char *argv[])
{
eightQueen();
system("pause");
}