zoukankan      html  css  js  c++  java
  • 八皇后问题

    #八皇后问题

    依然是递归 看和之前shooting的代码很像

    根据上述描述,我们可以得到如果两个皇后Q1(x, y)和Q2(row, col)不符合要求,则以下四个条件之一必符合。

    • x == row

    • y == col

    • x + y == row + col (斜向正方向)

    • x - y == row - col(斜向反方向)

    8个皇后都找到了安全位置代表棋局的成功,用一个长度为8的整数数组colume代表成功摆放的8个皇后.

    [数组索引代表棋盘的col向量,而数组的值为棋盘的row向量,所以(row,col)的皇后可以表示为(colume[col],col)]

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    #include <iostream>
    #include <cmath>

    #define QUEEN_NUM 8
    int ResultCounter = 0;

    void printResult(int colume[]);
    bool check(int colume[], int col);
    void QueenSolution(int colume[], int col);

    int main(void){
    //数组colume中存放的是行值
    //即假设col[0]==3,表明第1列中皇后在第4行上
    int colume[QUEEN_NUM] = {0};
    QueenSolution(colume, 0);
    std::cout << "Solution Total Count: " << ResultCounter << std::endl;
    }


    //输出数组中的一组结果
    void printResult(int colume[]){
    for(int i = 0; i < QUEEN_NUM; i++)
    std::cout << "(" << colume[i] << ", " << i << ") ";
    std::cout << std::endl;
    ResultCounter++;
    }

    //检查当前列col,在现有情况下,能否放置皇后
    //如果是以下四种情况,就返回false
    //1)x=row(在纵向不能有两个皇后)
    //2) y=col(横向)
    //3)col + row = y+x;(斜向正方向)
    //4) col - row = y-x;(斜向反方向)
    bool check(int colume[], int col){
    //因为提供的是列信息,我们就逐列进行检查
    for(int i = 0; i < col; i++)
    {
    if(colume[i] == colume[col] ||
    std::abs(colume[i] - colume[col]) == col - i )
    return false;
    }
    return true;
    }

    //尝试第col列上的所有解
    //即在第col列的所有行上依次检验
    //调用此函数时,表明从第0列到第col-1列都已经安置好了皇后
    void QueenSolution(int colume[], int col){
    if(col == QUEEN_NUM)
    {
    printResult(colume);
    return;
    }

    //新的一列中,皇后有可能在 任意 一行
    for(int i = 0; i < QUEEN_NUM; i++)
    {
    colume[col] = i; //将这个皇后放在第i行,进行检查
    if( check(colume, col) )
    QueenSolution(colume, col+1);
    }
    }
  • 相关阅读:
    #cat ora11g_ora_.trc
    Vue学习之路3-浅析Vue-cli搭建项目后的目录结构
    Vue学习之路2-项目初搭建
    Vue学习之路1-集成环境安装
    laravel中建立公共视图的方法
    Windows下Laravel5.5 的 Homestead 开发环境部署
    技术好文推荐
    中文文案排版指北
    消息队列的使用
    Laravel 验证中文本地化
  • 原文地址:https://www.cnblogs.com/xiaoerli520/p/9624126.html
Copyright © 2011-2022 走看看