八皇后问题

 经典的八皇后问题。。

 

#define LEN 8

int count = 0;

void eightQueen(int chess[][8], int row);
int isSafe(int chess[][8], int row, int col);

int main(int argc, char *argv[])
{
    int chess[LEN][LEN];
    int i, j;
    
    for(i = 0; i<LEN; i++)
    {
        for(j = 0; j < LEN; j++)
        {
            chess[i][j] = 0;
        }
    }
    
    eightQueen(chess, 0);
    printf("共有%d种方案", count);
    return 0;
}

void eightQueen(int (*chess)[8], const int row)
{
    int chess2[LEN][LEN];
    int i,j, k; 
    for(i = 0; i< LEN; i++)
    {
        for(j = 0; j< LEN; j++)
        {
            //printf("%d ", *(*((chess)+i)+j) );
            chess2[i][j] = *(*(chess+i)+j);
        }
    }

    if(row==LEN)
    {
        count += 1;
        printf("第 %d 种方案\n", count);
        for(i = 0; i< LEN; i++)
        {
            for(j = 0; j< LEN; j++)
            {
                printf("%d ", chess2[i][j]);
            }
            printf("\n");
        }
        printf("\n");
        
    }else {
        
        for(j = 0; j<LEN; j++)
        {
            for(k = 0; k<j; k++)
            {
                chess2[row][k] = 0;
            }
            
            if(!isSafe(chess2, row, j))
            {
                chess2[row][j] = 1;
                eightQueen(chess2, row+1);
            }
        }
    }
}

int isSafe(int (*chess)[8], const int row, const int col)
{
    int i,j,res = 0;
    
    for(i = row; i>=0; i--)
    {
        if(*(*(chess+i)+col) == 1)
        {
            res = 1;
            break;
        }
    }
    
    if(res == 1)
    {
        return res;
    }
    
    for(i = row-1, j = col-1; i>=0 && j>=0; i--, j--)
    {
        if(*(*(chess+i)+j) == 1)
        {
            res = 1;
            break;
         } 
    }
    
    if(res == 1)
    {
        return res;
    }
    
    for(i = row-1, j = col+1; i>=0 && j< LEN; i--, j++)
    {
        if(*(*(chess+i)+j) == 1)
        {
            res = 1;
            break;
         }
    } 
    
    if(res == 1)
    {
        return res;
    }
    
    return 0; 
}

eightQueen函数中,用k作循环的那一段超级重要,要不然每一行的结果之间就会相互影响。。。。。。

转载于:https://www.cnblogs.com/buerr/p/7383818.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值