数据结构练习(42)八皇后问题

http://zhedahht.blog.163.com/blog/static/2541117420114331616329/

思路:

1. 生成一组初始数据:01234567

2. 对这组数据进行排列组合,然后找满足8皇后解法的排列即:任何两个皇后都不能在同一列或对角线上

3. permutation的时候要注意,交换数据要从自身交换起,终止的时候是index == length。

#include <iostream>

using namespace std;



void PrintQueens(int column[], int length)

{

    for (int i = 0; i < length; ++i)

        cout << column[i] << ' ';

    cout << endl;

}



bool CheckQueens(int column[], int length)

{

    for (int i = 0; i < length; ++i)

        for (int j = i+1; j < length; ++j)

            if (j - i == column[i] - column[j] || i - j == column[i] - column[j])

                return false;

    return true;

}



void SwapValue(int& a, int& b)

{

    int t = a;

    a = b, b = t;

}



void Permutation(int column[], int length, int index)

{

    if (index == length)

    {

        if (CheckQueens(column, length))

            PrintQueens(column, length);

    }

    else

    {

        for (int i = index; i < length; ++i)

        {

            SwapValue(column[index], column[i]);

            Permutation(column, length, index + 1);

            SwapValue(column[index], column[i]);

        }

    }

}



void EightQueen()

{

    const int queens = 8;

    int column[queens+1];



    for (int i = 0; i < queens; ++i)

        column[i] = i;



    Permutation(column, queens, 0);

}





int main()

{

    EightQueen();

    return 0;

}

 

你可能感兴趣的:(数据结构)