@zwh8800
2017-08-23T10:24:08.000000Z
字数 578
阅读 191115
blog
归档
八皇后
算法
一个八皇后解法
#include <iostream>
#include <math.h>
using namespace std;
#define QUEEN 8
int board[QUEEN] = {0};
void Print()
{
static int count = 0;
cout << "Solve #" << ++count << ':' << endl;
for (int line = 0; line < QUEEN; ++line)
{
for (int col = 0; col < QUEEN; ++col)
{
if (board[line] == col)
cout << "●";
else
cout << "○";
}
cout << endl;
}
cout << endl;
}
bool Check(int line)
{
for (int y = 0; y < line; ++y)
if (board[y] == board[line] || abs(board[y] - board[line]) == abs(y - line))
return false;
return true;
}
void Put(int line)
{
if (line >= QUEEN)
{
Print();
return;
}
for (int col = 0; col < QUEEN; ++col)
{
board[line] = col;
if (Check(line))
Put(line + 1);
}
}
int main()
{
Put(0);
}