作者在 2010-05-25 12:47:50 发布以下内容
#include<iostream>
using namespace std;
int board[8] = {0,0,0,0,0,0,0,0};
void print_board();
int illegal(int);
void eight_queen(int);
int main()
{
eight_queen(0);
return 1;
}
void eight_queen(int i)
{
if (i >= 8)
print_board();
else
{
for (int j=0; j<8; j++)
{
board[i+1] = j;
if ( !illegal(i+1) )
eight_queen(i+1);
}
}
}
int illegal(int n)
{
for (int i=0; i< n-1; i++)
for (int j=i+1; j < n; j++)
{
if (board[i] == board[j] ||
abs(board[i]-board[j]) == abs(i-j) )
return 1;
}
return 0;
}
void print_board()
{
static int cnt = 1;
printf("ANS: %d\n", cnt++);
for (int i=0; i<8; i++)
{
for (int j=0; j<8; j++)
if (j==board[i])
printf("O");
else
printf(".");
cout << endl;
}
}
用递归做的
using namespace std;
int board[8] = {0,0,0,0,0,0,0,0};
void print_board();
int illegal(int);
void eight_queen(int);
int main()
{
eight_queen(0);
return 1;
}
void eight_queen(int i)
{
if (i >= 8)
print_board();
else
{
for (int j=0; j<8; j++)
{
board[i+1] = j;
if ( !illegal(i+1) )
eight_queen(i+1);
}
}
}
int illegal(int n)
{
for (int i=0; i< n-1; i++)
for (int j=i+1; j < n; j++)
{
if (board[i] == board[j] ||
abs(board[i]-board[j]) == abs(i-j) )
return 1;
}
return 0;
}
void print_board()
{
static int cnt = 1;
printf("ANS: %d\n", cnt++);
for (int i=0; i<8; i++)
{
for (int j=0; j<8; j++)
if (j==board[i])
printf("O");
else
printf(".");
cout << endl;
}
}
用递归做的