码迷,mamicode.com
首页 > 其他好文 > 详细

八皇后问题

时间:2018-10-04 09:32:05      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:lse   stdio.h   nbsp   --   return   span   状态   int   结束   

# 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;
}

 

八皇后问题

标签:lse   stdio.h   nbsp   --   return   span   状态   int   结束   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!