八皇后问题C++递归解法
#include <math.h>
#include <stdio.h>
#define FIRST_QUEUE_X 4 //position of first queue
struct Queen
{
int x ;
int y ;
};
class Q8
{
Queen queens[8];
int stack_top;
public:
Q8(int x0)
{
for(int i = 0 ; i < 8 ; i++)
{
queens[i].x = -1 ;
queens[i].y = i ;
}
stack_top = 0 ;
queens[stack_top].x = x0;
}
~Q8(){}
int cur_try_line()
{
return stack_top+1;
}
bool check_postion(int x,int y)
{
for(int i = 0 ; i <= stack_top ; i++)
{
if(queens[i].x == x || queens[i].y == y || abs(queens[i].x – x) == abs(queens[i].y – y))
return false ;
}
return true;
}
bool place_queen(Queen & queen)
{
queen.x++;
while(queen.x < 8)
{
if(check_postion(queen.x,queen.y))
return true ;
else
queen.x++;
}
queen.x = -1;
return false ;
}
bool place_queens()
{
while(stack_top < (8-1))
{
if(place_queen(queens[cur_try_line()]))
stack_top++;
else
{
stack_top–;
if(cur_try_line() < 0 ) //无法继续重试,摆放失败
return false;
}
}
return true ;
}
void dump()
{
for(int i = 0 ; i < 8 ; i++)
{
int j = 0 ;
for(j= 0 ; j < queens[i].x ; j++)
{
printf(“.”);
}
printf(“x”);
for(j++;j < 8 ; j++)
{
printf(“.”);
}
printf(“/n”);
}
}
};
int main()
{
Q8 q8(FIRST_QUEUE_X);
bool res = q8.place_queens();
if(res)
{
q8.dump();
}
else
{
printf(“can not place all queens/n”);
}
}