8 皇后区变化 - 安排回溯实施的数量 - 错误的输出
8 Queens Variation- Number of Arrangements Backtracking Implementation- Wrong Output
我正在尝试编写一个程序,在给定初始输入的情况下,它将计算 8X8 棋盘上 8 个皇后的不同排列的数量。由于某种原因,我的测试数据没有给我适当的输出。我想知道你们是否可以为我指出正确的方向。我没有编译器错误,但是在最后一个数据集上遇到了分段错误。
我尝试过调试,但我想我刚刚看了很长时间的代码,以至于我开始混淆自己。如果有人能给我一些帮助,我将不胜感激。谢谢。我认为我的问题要么在isSafe函数中,要么在solveNQUtil方法中的终止条件中。
我的测试数据,(每一行都是行、列、我的输出和预期结果的单独情况):
r c Output Expected output
1 2 14 8
6 7 8 14
7 8 312 8
8 8 312 4
2 2 4 16
2 4 12 8
1 7 8 8
8 3 Seg Fault 16
我的代码:
#include <iostream>
#include<stdio.h>
using namespace std;
int arrangements = 0;
int column_start = 0;
/* A utility function to print solution */
void printSolution(int board[8][8])
{
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
if( board[i][j] ) {
printf(" Q ");
}else{
printf(" . ");
}
//printf(" %d ", board[i][j]);
printf("n");
}
}
bool isSafe(int board[8][8], int row, int col)
{
int i, j;
for (i = 0; i < 8; i++){
if (board[row][i]){
return false;
}
}
for (i = row, j = col; i >= 0 && j >= 0; i--, j--){
if (board[i][j]){
return false;
}
}
for (i = row, j = col; i < 8 && j < 8; i++, j++){
if (board[i][j]){
return false;
}
}
for (i = row, j = col; j >= 0 && i < 8; i++, j--) {
if (board[i][j]){
return false;
}
}
for( i = row, j = col; j < 8 && i >= 0; i--, j++){
if (board[i][j]){
return false;
}
}
return true;
}
void solveNQUtil(int board[8][8], int queens, int col)
{
if (queens >= 8){
printSolution(board);
cout << "---------------------------------------------" << endl;
arrangements++;
}else{
for (int i = 0; i < 8; i++){
if ( isSafe(board, i, col) ){
board[i][col] = 1;
int tempCol = (col + 1) % 8;
solveNQUtil(board, queens + 1, tempCol );
//backtrack
board[i][col] = 0;
}
}
}
}
bool solveNQ(){
int row = 0;
int col = 0;
int board[8][8];
for(int i = 0; i < 8; i++){
for(int j = 0; j < 8; j++){
board[i][j] = 0;
}
}
cin >> row >> col;
board[row][col] = 1;
column_start = col;
solveNQUtil(board, 1, (col + 1) % 8);
//solveNQUtil(board,0,0);
if(arrangements == 0){
printf("Solution does not exist");
return false;
}
return true;
}
int main(){
solveNQ();
cout << "Arrangements: " << arrangements << endl;
return 0;
}
只要
你的row < 8 and col < 8
你得到的输出是正确的。您给出的预期输出是错误的。
当row = 8 or col = 8
数组索引超出范围并尝试将值分配给一些未分配给数组的内存时。
- 如果另一个内存是空闲的,它将存储在其中并且不会有任何错误,但您的输出将是错误的,因为您的第一个女王在板外,但您告诉您的
solveNQUtil
板中有一个女王。 - 但是,如果其他内存已经分配给其他内存,则会出现分段错误。
你把它编程为从零索引开始,所以你只需要将输入递减一。所有输出都将与预期结果匹配。
cin >> row >> col;
row--;
col--;
if (row < 0 || row >= 8 || col < 0 || col >= 8) return false;
相关文章:
- 输出错误,问题是找到总和5000位数字cpp
- 使用复制构造函数的程序输出错误
- 异或字符串加密/解密输出错误
- 在linux上使用g++输出错误,在windows上更正
- 使用递归函数 (c++) 将长字符串转换为整数时输出错误
- ECDSA 密钥对生成输出错误
- fscanf() 输出错误的值
- 输入 1024 后十进制到二进制转换的输出错误?
- 输出错误命令的条件语句
- cuSparse (cusparseDcsrgemm) 中的矩阵乘法输出错误的结果
- 为什么 du -sh 输出错误大小的内存映射文件
- VS2017 的输出错误,但 mingw 有效
- 如何使FFMPEG C 代码不输出错误消息
- 乘以时输出错误.这是我编译器中的错误吗?C
- 输出错误:两个不同编译器上的不同输出:Prime Cryptarithm USACO
- 为什么输出错误崩溃
- C++输入/输出错误
- 尝试用 c++ 制作一个简单的加法器.编译成功,但输出错误
- 当我使用此合并排序代码运行时,输出错误
- 递归功能输出错误的值