回溯 八皇后

回溯 八皇后


题意

> 棋子不能在同一行,同一列,以及同一对角线。
> 输出所有符合要求的情况。
  • 步骤:用计数器统计次数,按列写出全排列,再枚举任意两个棋子,如果不符合条件,则计数器不变。与直接递归不同的是,用到了剪枝技巧,如果不符合要求,则立即开始下一个状况
#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

猜你喜欢

转载自www.cnblogs.com/Kirarrr/p/10336489.html