主题:8皇后位结构版
#include <iostream>
using namespace std;
typedef unsigned char byte;
int tot = 0;
bool check (byte board[8], int row)
{
byte a = board[row] << 1;
for (int i = row - 1; i >= 0 && a; a <<= 1, --i)
if (a & board[i])
return false;
a = board[row] >> 1;
for (int i = row - 1; i >= 0 && a; a >>= 1, --i)
if (a & board[i])
return false;
a = board[row];
for (int i = row - 1; i >= 0; --i)
if (a & board[i])
return false;
return true;
}
void queen8 (byte board[8], int row)
{
if (row >= 8) {
tot++;
for (int i = 0; i < 8; ++i) {
for (byte bit = 1; bit; bit <<= 1)
cout << ((bit & board[i]) != 0) << ' ';
cout << '\n';
}
cout << endl;
return;
}
for (board[row] = 1; board[row]; board[row] <<= 1)
if (check (board, row) == true)
queen8 (board, row + 1);
}
int main ()
{
byte board[8] = {0};
queen8 (board, 0);
cout << tot << endl;
system ("pause");
return 0;
}
using namespace std;
typedef unsigned char byte;
int tot = 0;
bool check (byte board[8], int row)
{
byte a = board[row] << 1;
for (int i = row - 1; i >= 0 && a; a <<= 1, --i)
if (a & board[i])
return false;
a = board[row] >> 1;
for (int i = row - 1; i >= 0 && a; a >>= 1, --i)
if (a & board[i])
return false;
a = board[row];
for (int i = row - 1; i >= 0; --i)
if (a & board[i])
return false;
return true;
}
void queen8 (byte board[8], int row)
{
if (row >= 8) {
tot++;
for (int i = 0; i < 8; ++i) {
for (byte bit = 1; bit; bit <<= 1)
cout << ((bit & board[i]) != 0) << ' ';
cout << '\n';
}
cout << endl;
return;
}
for (board[row] = 1; board[row]; board[row] <<= 1)
if (check (board, row) == true)
queen8 (board, row + 1);
}
int main ()
{
byte board[8] = {0};
queen8 (board, 0);
cout << tot << endl;
system ("pause");
return 0;
}