八皇后问题

来源:互联网 发布:java学徒0基础骗局 编辑:程序博客网 时间:2024/05/19 07:07

问题描述:
Write an algorithm to print all ways of arranging eight queens on a chess board so that none of them share the same row, column or diagonal.
用DFS层层按条件搜索,下一层的位置只有满足与上一层位置点不在同一行、同一列和同一条对角线上(包括主对角线和副对角线)。
用一个一维数组来存储整个棋盘的信息,c[i] = j表示第i行的皇后要放在j列,如果当前行为r,皇后要放在c[r]列。同列满足:c[r]==c[j]; 同对角线有两种可能,即主对角线方向和副对角线方向。 主对角线方向满足,行之差等于列之差:r-j==c[r]-c[j]; 副对角线方向满足, 行之差等于列之差的相反数:r-j==c[j]-c[r],代码如下:

// EightQueen.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include <iostream>using namespace std;int c[20], n = 8, cnt = 0;void print() {    for (int i = 0; i<n; ++i) {        for (int j = 0; j<n; ++j) {            if (j == c[i]) cout << "1 ";            else cout << "0 ";        }        cout << endl;    }    cout << endl;}void search(int r) {//递归地搜索可行解    if (r == n) {        print();        ++cnt;        return;    }    for (int i = 0; i<n; ++i) {        c[r] = i;        int ok = 1;//满足放置条件的标志位        for (int j = 0; j<r; ++j)            if (c[r] == c[j] || r - j == c[r] - c[j] || r - j == c[j] - c[r]) {                ok = 0;                break;            }        if (ok) search(r + 1);    }}int main() {    search(0);    cout << cnt << endl;    return 0;}

共有92组解
参考:
http://blog.163.com/yichangjun1989@126/blog/static/13197202820145226051666/

1 0