Kirarrr

导航

递归 八皇后

递归 八皇后


题意

> 棋子不能在同一行,同一列,以及同一对角线。
> 输出所有符合要求的情况。
  • 步骤:用计数器统计次数,按列写出全排列,再枚举任意两个棋子,如果不符合条件,则计数器不变。
#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) {
        bool flag = true;
        for (int i = 1; i <= n; i++) {
            for (int j = i + 1; j <= n; j++) {
                if (abs(i - j) == abs(p[i] - p[j])) {
                    flag = false;
                }
            }
        }
        if (flag) count++;
        return;
    }
    for (int x = 1; x <= n; x++) {
        if (hashTable[x] == false) {
            p[index] = x;
            hashTable[x] = true;
            generateP(index + 1);
            hashTable[x] = false;
        }
    }
}

int main() {
    n = 8;
    generateP(1);
    printf("%d", count);
    return 0;
}

输出结果 92

posted on 2019-01-30 00:23  Kirarrr  阅读(100)  评论(0编辑  收藏  举报