zoukankan      html  css  js  c++  java
  • 数据结构练习(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;
    }
    -------------------------------------------------------

    kedebug

    Department of Computer Science and Engineering,

    Shanghai Jiao Tong University

    E-mail: kedebug0@gmail.com

    GitHub: http://github.com/kedebug

    -------------------------------------------------------

  • 相关阅读:
    Windows Mobile下创建cmwap接入点
    我的云之旅hadoop单机设置(2)
    ssh登录
    我的云之旅前言(1)
    实时搜索将是下一个核心
    cassandra索引目录
    图书大甩卖(操作系统、C语言、Linux) 已成交
    ehcache实例
    google推出语音搜索
    百姓网看起来还行
  • 原文地址:https://www.cnblogs.com/kedebug/p/2829063.html
Copyright © 2011-2022 走看看