c++ - 8皇后程序-象棋版
C++- 8 Queens program- chess edition
我被分配使用排列代码,并将其转换为象棋棋盘上的8皇后程序。
我想我已经完成了,但是我的输出一直给堆栈溢出,我找不到它在哪里,这太疯狂了!
下面是我的代码#include <iostream>
#include <iomanip>
using namespace std;
char board[8][8];
void clearBoard();
void attempt(int n, int level, int possibility);
void placeQueen(int level, int possibility);
void removeQueen(int level, int possibility);
bool currentPathSuccess(int n, int level, int possibility);
bool currentPathStillViable(int level, int possibility);
void processSuccessfulPath(int n);
int main()
{
int n;
clearBoard();
cout << "Permutation of integers from 1 to ? ";
cin >> n;
for (int i = 1; i <= n; i++){
for (int j = 1; j <= n; j++)
{
attempt(n, i, j);
}
}
system("pause");
return 0;
}
void clearBoard()
{
for (int i = 0; i < 8; i++)
for (int j = 0; j < 8; j++)
board[i][j] = '_';
}
void attempt(int n, int level, int possibility)
{
placeQueen(level, possibility);
if (currentPathSuccess(n, level, possibility))
{
processSuccessfulPath(n);
}
else if (currentPathStillViable(level, possibility))
for (int i = 0; i <= n; i++)
attempt(n, level + 1, possibility + 1);
removeQueen(level, possibility);
}
void placeQueen(int level, int possibility)
{
board[level][possibility] = 'Q';
}
void removeQueen(int level, int possibility)
{
board[level][possibility] = '_';
}
bool currentPathSuccess(int n, int level, int possibility)
{
bool success = true;
int i = 0;
int j = 0;
if (n > level)
success = false;
else
{
while ((i <= level - 1) && success)
{
success = board[i][j] != board[level][possibility];
i++;
}
}
return success;
}
bool currentPathStillViable(int level, int possibility)
{
bool viable = true;
int i = 0;
int j = 0;
while ((i <= level - 1) && viable)
{
viable = board[i][j] /*!= board[level][possibility]*/;
i++;
}
return viable;
}
void processSuccessfulPath(int n)
{
for (int i = 0; i <= n; i++)
{
for (int j = 0; j <= n; j++)
{
cout << setw(3) << board[i][j];
}
cout << endl;
}
cout << endl;
}
您的attempt()
递归函数调用导致堆栈溢出。有问题。查看函数内部的break条件
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- C++,系统无法执行指定的程序
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 在VS代码中交叉编译Windows与Linux上的MinGW的SDL程序
- C++ Windows 驱动程序MSB3030无法复制该文件,因为它找不到
- 重载操作程序时出错>>用于类中的字符串 memebr
- 获取日期异步信号安全吗?如果在信号处理程序中使用,它会导致死锁吗
- 试图在visual studio上用C++创建一个桌面应用程序
- 模板元程序查找相似的连续类型名称
- FFmpeg:制作一个应用程序比直接使用ffmepg更好吗
- 如何通过cpp程序运行shell脚本
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- IPC使用多个管道和分支进程来运行Python程序
- 如何将c++程序的一些输出传递给shell,以便在shell中使用
- 使用C++程序合并排序没有得到正确的输出
- 基于boost的程序的静态链接——zlib问题
- 程序崩溃并显示"std::out_of_range"错误
- 在C应用程序中运行C++(带有STL)函数
- 使用mongocxx驱动程序时包含头文件问题
- 如何在c++程序中找到函数的地址