我正在编写臭名昭著的N-Queens问题的代码。但我有个问题。程序正在执行,但没有给出预期的输出,因为我遇到了一个问题,因为矩阵board的值没有改变,并且将最初的值分配给了board,即0分配给了board的每个元素。可能的逻辑错误是什么?
以下是代码
#include<iostream>
using namespace std;
int board[4][4];
int isAttacked(int i, int j){
for(int k = 0; k < 4; k++){
if(board[i][k] == 1 || board[k][j] == 1) return true; // checking for the rows and columns
}
for(int k = 0; k < 4; k++){
for(int l = 0; l < 4; l++){
if(((k + l) == (i + j))|| ((k - l) == (i - j))){ // checking for the diagonals
if(board[k][l] == 1) return true;
}
}
}
return false;
}
int nQueen(int N){
if(N == 0) return true;
for(int i = 0; i < 4; i++){
for(int j = 0; j < 4; j++){
if(!isAttacked(i, j)){
board[i][j] == 1;
if(nQueen(N - 1))
return true;
board[i][j] = 0;
}
}
}
return false;
}
void print(){
for(int i = 0; i < 4; i++){
for(int j = 0; j < 4; j++){
cout << board[i][j];
}
cout << "\n";
}
}
int main(){
for(int i = 0; i < 4; i++){
for(int j = 0; j < 4; j++){
board[i][j] = 0;
}
}
nQueen(4);
print();
return 0;
}预期o/p应为:
0 1 0 0
0 0 0 1
1 0 0 0
0 0 1 0实际o/p:
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0发布于 2019-09-19 20:22:35
所以,我调试了我的代码,这是一个愚蠢的错误:(错误是在nQueen()中使用==运算符而不是=运算符。它应该是
for(int j = 0; j < 4; j++){
if(!isAttacked(i, j) && (board[i][j] != 1)){
*board[i][j] = 1;*
if(nQueen(N - 1))
return true;而不是
for(int j = 0; j < 4; j++){
if(!isAttacked(i, j) && (board[i][j] != 1)){
*board[i][j] == 1;*
if(nQueen(N - 1))
return true;以下是经过调试的代码。
#include<iostream>
using namespace std;
int board[4][4];
int isAttacked(int i, int j){
for(int k = 0; k < 4; k++){
if(board[i][k] == 1 || board[k][j] == 1) return 1; // checking for the rows and columns
}
for(int k = 0; k < 4; k++){
for(int l = 0; l < 4; l++){
if(((k + l) == (i + j)) || ((k - l) == (i - j))){ // checking for the diagonals
if(board[k][l] == 1)
return 1;
}
}
}
return 0;
}
bool nQueen(int N){
if(N == 0) return true;
for(int i = 0; i < 4; i++){
for(int j = 0; j < 4; j++){
if(!isAttacked(i, j) && (board[i][j] != 1)){
board[i][j] = 1;
if(nQueen(N - 1))
return true;
board[i][j] = 0;
}
}
}
return false;
}
void print(){
for(int i = 0; i < 4; i++){
for(int j = 0; j < 4; j++){
cout << board[i][j];
}
cout << "\n";
}
}
int main(){
nQueen(4);
print();
return 0;
}https://stackoverflow.com/questions/57935773
复制相似问题