首页 > 其他 > 详细

八皇后问题

时间:2018-10-04 04:15:34      阅读:159      评论:0      收藏:0      [点我收藏+]
# include <stdio.h>
# include <memory.h>
# include <stdbool.h>

int count = 0;

bool is_safe(int row, int col, int chessp[][8])
{
    int i, j;
    
    /*判断列*/
    for(j = 0; j < row; ++j)
    {
        if (chessp[j][col])
        {
            return false;
        }
    }
    
    /*判断左上*/
    for (i = row-1, j = col-1; i >= 0 && j >=0; --i, --j)
    {
        if(chessp[i][j])
        {
            return false;
        }
    }
    
    /*判断右上*/
    for(i = row-1, j = col+1; i >= 0 && j < 8; --i, ++j)
    {
        if(chessp[i][j])
        {
            return false;
        }
    }
    
    return true;
}

void queen(int row, int col, int chessf[][8])
{
    int i, j;
    
    /*结束条件*/
    if (row == 8)
    {
        count++;
        printf("第%d种:\n", count);
        for(i = 0; i < 8; ++i)
        {
            for(j = 0; j < 8; ++j)
            {
                printf("%d ", chessf[i][j]);
            }
            printf("\n");
        }
        
        printf("\n\n"); 
        return;
    }
    else
    {
        for(i = 0; i < col; ++i)
        {
            if(is_safe(row, i, chessf))
            {
                chessf[row][i] = 1;
                queen(row+1, col, chessf);     //递归 
                chessf[row][i] = 0;           //回溯 
            }
        }
    }
}

int main(void)
{
    int chess[8][8];
    memset(chess, 0, sizeof(chess));        //开始状态,棋盘置空 
    queen(0, 8, chess);
    return 0;
}

 

八皇后问题

原文:https://www.cnblogs.com/zcxhaha/p/9739794.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!