用C++实现的八皇后问题
2024-10-08 23:35:59
我是一个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;
}
最新文章
- WordPress建站 新手入门
- http post和put区别
- 安卓,支付宝app登录时,提示 服务器安全证书已过期或不可信任,请问怎么解决
- c#程序中使用";like“查询access数据库查询为空的问题
- centos7.2 默认启动内核修改
- 【Android 基础】Animation 动画介绍和实现
- CARP-VRRP-HSRP
- linux 定时任务 crontab
- 第33条:用EnumMap代替序数索引
- python 备份压缩传输
- 新疆大学ACM-ICPC程序设计竞赛五月月赛(同步赛)A	Red Rover
- java小白之面向对象
- su命令
- VSCode之快捷键和常用插件
- ssh 配置免密失败
- 文档对象模型DOM(二)
- Serializable 介绍
- [LeetCode&;Python] Problem 804. Unique Morse Code Words
- 『编程题全队』Alpha 阶段冲刺博客集合
- Promise的并行和串行
热门文章
- [Android] Volley源代码分析(五岁以下儿童)Q \\ u0026一个
- jQuery EasyUI API - Base - Draggable [原创汉化官方API]
- 2014年3I工作室成员的正式名单
- JAVA开发语言基础
- [转]网上看到的关于C中内存分配的描述
- 验证编辑方法(Edit method)和编辑视图(Edit view)
- Vijos:P1001谁拿了最多奖学金
- Visual Stuido也有非常多的快捷键
- Unkown2
- .NET 利用反射将对象数据添加到数据库