//
#include "time.h"
/** 在新行中第pos个位置打印一个*号
*/
void print_star(int pos)
{
char str[] = "| |\n";
str[pos*2] = '*';
printf(str);
}
/** get a random num between 0,1,2,...7
*/
int get_rand_num()
{
return rand()%8;
}
/** 打印8×8矩阵
*/
void print_flag(bool flag[8][8])
{
//打印星号矩阵
for(int i=0;i<8;i++){
for(int j=0;j<8;j++){
if(flag[i][j] == true){
print_star(j+1);
break;
}
}
}
//打印0-1矩阵
for(int i=0;i<8;i++){
for(int j=0;j<8;j++){
printf(" %d", flag[i][j]==1?0:1);
}
printf("\n");
}
}
/** result = (i<=num<=j)
*/
bool isBetween(int num, int i, int j)
{
return (num>=i)&&(num<=j);
}
/** test whether flag[i][j] can be true
对于flag[8][8]矩阵,判断可否在第row行,第col列放入一个棋子
*/
bool test_value(bool flag[8][8], int row, int col)
{
//判断横
for(int i=0;i<8;i++){
if(true == flag[i][col]){
return false;
}
}
//判断竖
for(int j=0;j<8;j++){
if(true == flag[row][j]){
return false;
}
}
//判断斜方向
for(int i=1;i<8;i++){
if(isBetween(row-i, 0, 7)&&isBetween(col-i, 0, 7)){
if(true == flag[row-i][col-i]){
return false;
}
}
else{
break;
}
}
//判断斜方向
for(int i=1;i<8;i++){
if(isBetween(row+i, 0, 7)&&isBetween(col+i, 0, 7)){
if(true == flag[row+i][col+i]){
return false;
}
}
else{
break;
}
}
//判断斜方向
for(int i=1;i<8;i++){
if(isBetween(row-i, 0, 7)&&isBetween(col+i, 0, 7)){
if(true == flag[row-i][col+i]){
return false;
}
}
else{
break;
}
}
//判断斜方向
for(int i=1;i<8;i++){
if(isBetween(row+i, 0, 7)&&isBetween(col-i, 0, 7)){
if(true == flag[row+i][col-i]){
return false;
}
}
else{
break;
}
}
flag[row][col] = true;
return true;
}
#define RAND_NUM 20
//递归函数
bool recursive(bool flag[8][8], int i)
{
if(i==8)
return true;
int num = 0;
while(num<RAND_NUM){
int j = get_rand_num();
if(test_value(flag, i, j)){
break;
}
num++;
}
if(num<RAND_NUM)
return recursive(flag, i+1);
else
return false;
}
/** get a queen fig
*/
bool get_queen_fig(bool flag[8][8])
{
//棋局初始化
for(int i=0;i<8;i++){
for(int j=0;j<8;j++){
flag[i][j] = false;
}
}
return recursive(flag, 0);
}
#define LOOP_NUM 30
int _tmain(int argc, _TCHAR* argv[])
{
srand(time(0));
for(int i=1;i<=8;i++)
print_star(i);
bool flag[8][8];
int loops = 0;
do
{
loops++;
if(loops>LOOP_NUM)
{
break;
}
printf("has trying get a queen figure for %d times\n", loops);
}
while(false == get_queen_fig(flag));
if(loops>LOOP_NUM)
printf("failed to get a queen figure!\n");
else{
printf("succeed to get a queen figure!\n");
print_flag(flag);
}
return 0;
}