我是一个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;
}

最新文章

  1. WordPress建站 新手入门
  2. http post和put区别
  3. 安卓,支付宝app登录时,提示 服务器安全证书已过期或不可信任,请问怎么解决
  4. c#程序中使用&quot;like“查询access数据库查询为空的问题
  5. centos7.2 默认启动内核修改
  6. 【Android 基础】Animation 动画介绍和实现
  7. CARP-VRRP-HSRP
  8. linux 定时任务 crontab
  9. 第33条:用EnumMap代替序数索引
  10. python 备份压缩传输
  11. 新疆大学ACM-ICPC程序设计竞赛五月月赛(同步赛)A Red Rover
  12. java小白之面向对象
  13. su命令
  14. VSCode之快捷键和常用插件
  15. ssh 配置免密失败
  16. 文档对象模型DOM(二)
  17. Serializable 介绍
  18. [LeetCode&amp;Python] Problem 804. Unique Morse Code Words
  19. 『编程题全队』Alpha 阶段冲刺博客集合
  20. Promise的并行和串行

热门文章

  1. [Android] Volley源代码分析(五岁以下儿童)Q \\ u0026一个
  2. jQuery EasyUI API - Base - Draggable [原创汉化官方API]
  3. 2014年3I工作室成员的正式名单
  4. JAVA开发语言基础
  5. [转]网上看到的关于C中内存分配的描述
  6. 验证编辑方法(Edit method)和编辑视图(Edit view)
  7. Vijos:P1001谁拿了最多奖学金
  8. Visual Stuido也有非常多的快捷键
  9. Unkown2
  10. .NET 利用反射将对象数据添加到数据库