手机版
你好,游客 登录 注册
背景:
阅读新闻

用C++实现的八皇后问题

[日期:2017-01-12] 来源:Linux社区  作者:yonggandefeng [字体: ]

我是一个C++初学者,控制台实现了一个八皇后问题。

代码如下:

//"八皇后问题"V1.0
//李国良于2017年1月11日编写完成

#include <iostream>
#include <Windows.h>

using namespace std;
const int ArSize = 8;//这个数等于几,就是几皇后。
int num = 0;
void solve(bool arr[ArSize][ArSize], int row);
bool check(bool arr[ArSize][ArSize], int row, int column);
void outPut(bool arr[ArSize][ArSize]);

int main()
{
    SetConsoleTitle("八皇后问题");
    bool chessboard[ArSize][ArSize];
    for (auto &i : chessboard)
    {
        for (auto &j : i)
        {
            j = false;
        }
    }
    solve(chessboard, 0);
    cout << "八皇后问题共有" << num << "种解!" << endl;
    system("pause");
    return 0;
}

void solve(bool arr[ArSize][ArSize], int row)
{
    for (int column = 0; column < ArSize; ++column)
    {
        arr[row][column] = true;
        if (check(arr, row, column))
        {
            if (row + 1 == ArSize)
            {
                outPut(arr);
            }
            else
            {
                solve(arr, row + 1);
            }
        }
        arr[row][column] = false;
    }
}

bool check(bool arr[ArSize][ArSize], int row, int column)
{
    if (row == 0)
    {
        return true;
    }
    int i, j;
    for (i = 0; i < row; ++i)
    {
        if (arr[i][column])
        {
            return false;
        }
    }
    i = row - 1;
    j = column - 1;
    while (i >= 0 && j >= 0)
    {
        if (arr[i][j])
        {
            return false;
        }
        --i;
        --j;
    }
    i = row - 1;
    j = column + 1;
    while (i >= 0 && j <= ArSize - 1)
    {
        if (arr[i][j])
        {
            return false;
        }
        --i;
        ++j;
    }
    return true;
}

void outPut(bool arr[ArSize][ArSize])
{
    ++num;
    cout << "**********************" << num << "*********************" << endl;
    for (int i = 0; i < ArSize; ++i)
    {
        for (int j = 0; j < ArSize; ++j)
        {
            cout << arr[i][j] << " ";
        }
        cout << endl;
    }
    cout << "*********************************************" << endl;
}

本文永久更新链接地址http://www.linuxidc.com/Linux/2017-01/139475.htm

linux
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款