我正在尝试编写一个程序,给定一个初始输入,将计算在8X8的棋盘上放置8个皇后的不同排列数量。但是,我的测试数据并没有给我适当的输出。我想知道你们能否指点我方向。虽然我的编译器没有错误,但我在最后一个数据集上得到了分段错误。
我已经尝试过调试,但我认为我只是看着我的代码太久,开始困惑自己了。如果有人能给我一些帮助,我会非常感激。谢谢。我认为我的问题可能要么在isSafe函数中,要么在solveNQUtil方法中的停止条件。
我的测试数据(每行是单独的行、列、我的输出和期望结果):
我已经尝试过调试,但我认为我只是看着我的代码太久,开始困惑自己了。如果有人能给我一些帮助,我会非常感激。谢谢。我认为我的问题可能要么在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;
}