我正在编写臭名昭著的 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
实际开工:
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
最佳答案
所以,我调试了我的代码,这是一个愚蠢的错误 :( 错误是在 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;
}
关于c++ - 未获得 N-Queens 问题的预期输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57935773/