递归解n皇后

来源:互联网 发布:鸡汤网络中是什么意思 编辑:程序博客网 时间:2024/04/30 20:51

题目描述:在N*N的方格棋盘放置了N个皇后,使得它们不相互攻击(即任意2个皇后不允许处在同一排,同一列,也不允许处在与棋盘边框成45角的斜线上。你的任务是,对于给定的N,求出有多少种合法的放置方法。


该算法有诸多解法,解的范围有很大区别。此处仅给出递归的解法,其他部分解法将在以后说明。


1 . 代码:

#include<iostream>using namespace std;const int N = 20;int q[N];void display(int n) {    static int count = 0;    int i, j;    cout << "第" << ++count << "个解为:\n";    for (i = 1; i <= n; i++)    {        for (j = 1; j <= n; j++) {            if (j == q[i])                cout << "■ ";            else                cout << "□ ";        }        cout << endl;    }    cout << endl;}int place(int k, int j) {    int i = 1;    while (i < k) {        if (q[i] == j || abs(q[i] - j) == abs(k - i)) {            return 0;        }        i++;    }    return 1;}void queen(int k, int n) {    int j;    if (k > n)        display(n);    else        for (j = 1; j <= n; j++) {            if (place(k, j)) {                q[k] = j;                queen(k + 1, n);            }        }}int main(){    int num;p:    cout << "please input a number:";    cin >> num;    if (num > 20) {        cout << "number过大,不能求解!";    }    else {        cout << num << "皇后的求解如下:" << endl;        queen(1, num);        cout << endl;    }    goto p;    return 0;}

goto语句用于测试。

2 . 运行结果

递归解n皇后

0 0