zoukankan      html  css  js  c++  java
  • 回溯 八皇后

    回溯 八皇后


    题意

    > 棋子不能在同一行,同一列,以及同一对角线。
    > 输出所有符合要求的情况。
    
    • 步骤:用计数器统计次数,按列写出全排列,再枚举任意两个棋子,如果不符合条件,则计数器不变。与直接递归不同的是,用到了剪枝技巧,如果不符合要求,则立即开始下一个状况
    #include <cstdio>
    #include <algorithm>
    
    const int maxn = 100;
    int n, p[maxn], hashTable[maxn] = {false};
    int count = 0;
    
    void generateP(int index) {
        if (index == n + 1) {
            count++;
            return;
        }
        for(int x = 1; x <= n; x++) {
            if(hashTable[x] == false) {
                bool flag = true;
                for (int pre = 1; pre < index; pre++) {
                    if (abs(index - pre) == abs(x - p[pre])) {
                        flag = false;
                        break;
                    }
                }
                if (flag) {
                    p[index] = x;
                    hashTable[x] = true;
                    generateP(index + 1);
                    hashTable[x] = false;
                }
            }
        }
    }
    
    int main() {
        n = 8;
        generateP(1);
        printf("%d", count);
        return 0;
    }
    
    

    输出结果 92

  • 相关阅读:
    参考__JAVA
    债券价格和通胀率
    C++ 面试题
    欧式和美式期权
    explicit
    smart pointer
    const pointer
    manacher-马拉车算法
    输入有空格的字符串的2种方法
    bind()与connect()——计网中socket的使用
  • 原文地址:https://www.cnblogs.com/Kirarrr/p/10336489.html
Copyright © 2011-2022 走看看