基本思想是,使用stack保存已经放置的皇后的位置。
struct chess_point
{
int x;
int y;
};
struct chess_point g_stack[8];
int g_top;
void stack_init(void)
{
g_top = -1;
}
void stack_push( struct chess_point point)
{
g_top++;
g_stack[g_top] = point;
}
struct chess_point stack_pop(void )
{
struct chess_point p = g_stack[g_top];
g_top--;
return p;
}
int stack_size ( void )
{
return g_top + 1;
}
int stack_check_compatibility( struct chess_point p)
{
int i;
for( i = g_top; i >= 0; i--)
{
if( g_stack[i].x == p.x || g_stack[i].y == p.y ||
g_stack[i].x + g_stack[i].y == p.x + p.y ||
g_stack[i].x - g_stack[i].y == p.x - p.y)
{
return 0;
}
}
return 1;
}
int total = 0;
void search( int N)
{
stack_init();
struct chess_point p = {0, 0};
do
{
if( stack_size() >= N || p.y >= N)
{
p = stack_pop();
p.y++;
// printf("#1 x = %d, y = %d, stack size:%d\n", p.x, p.y, g_top);
}
else
{
while( ( p.y < N) && ( stack_check_compatibility(p) == 0 ))
{
p.y++;
// printf("#2 x = %d, y = %d, stack size: %d\n", p.x, p.y, g_top);
}
if( p.y < N)
{
stack_push(p);
if(stack_size() >= N)
{
total++;
}
p.x++; p.y = 0;
// printf("#3 x = %d, y = %d, stack size:%d\n", p.x, p.y, g_top);
}
}
}
while( p.x > 0|| p.y < N);
}
int main(void)
{
search(4);
return 0;
}
参考了 数据结构(邓俊辉版)