迭代法求解八皇后问题

基本思想是,使用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;
}

参考了 数据结构(邓俊辉版)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值