八皇后(递归)

#include <iostream>
using namespace std;
class EightQueens
{
public:
    EightQueens()
    {
        count = 0;
        for (int i = 0; i < 8; i++)
            for (int j = 0; j < 8; j++)
                chess[i][j] = false;
        for (int i = 0; i < 8; i++)
            perms[i] = i;
    }
    void solve()
    {
        perm(0);
    }
private:
    int count;
    bool chess[8][8];
    int perms[8];
    void perm(int start);
    bool isSafe(int x, int y);
    void _swap(int &x, int &y)
    {
        int temp = x;
        x = y;
        y = temp;
    }
};

void EightQueens::perm(int start)
{
    if (start == 8)   //此处若改为7则出错
    {
        cout << "第" << ++count << "种情况:" << endl;
        for (int i = 0; i < 8; i++)
        {
            for (int j = 0; j < 8; j++)
            {
                if (chess[i][j])
                    cout << "*";
                else
                    cout << "-";
            }
            cout << endl;
        }
        cout << endl;
        return;
    }
    for (int i = start; i < 8; i++)
    {
        _swap(perms[start], perms[i]);
        if (isSafe(start, perms[start]))
        {
            chess[start][perms[start]] = true;
            perm(start + 1);
            chess[start][perms[start]] = false;
        }

        _swap(perms[start], perms[i]);
    }
}
bool EightQueens::isSafe(int x, int y)
{
    bool safe = true;
    int i = x, j = y;
    do
    {
        if (chess[i][j])
        {
            safe = false;
            break;
        }
        i--, j--;
    } while (i >= 0 && j >= 0);
    if (!safe) return false;
    i = x, j = y;
    do
    {
        if (chess[i][j])
        {
            safe = false;
            break;
        }
        i++, j++;
    } while (i < 8 && j < 8);
    if (!safe) return false;
    i = x, j = y;
    do
    {
        if (chess[i][j])
        {
            safe = false;
            break;
        }
        i++, j--;
    } while (i < 8 && j >= 0);
    if (!safe) return false;
    i = x, j = y;
    do
    {
        if (chess[i][j])
        {
            safe = false;
            break;
        }
        i--, j++;
    } while (i >= 0 && j < 8);
    if (!safe) return false;
    return true;
}

int main()
{
    EightQueens e;
    e.solve();
    return 0;
}

 

    原文作者:八皇后问题
    原文地址: https://blog.csdn.net/hcmdghv587/article/details/82534407
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞