Reputation: 33
While trying to solve the n-queens problem in c++. I came across this error where I would get the correct answer but when returning the array pointer, I end up getting garbage numbers instead of my answer. The weird part about this is that I use recursion to solve the problem and I only get garbage numbers when the recursion gets used (even though it correctly passes through the recursion). The array is completely correct before returning it.
int* Successor(int board[], int n) {
bool currentlyLegal = isLegalPosition(board, n);
int firstZero = -1;
int templast;
for(int i = 0; i < n; i++) {
if(board[i] == 0) {
firstZero = i;
break;
}
}
if(currentlyLegal) {
if(firstZero != -1) {
for(int i = 1; i < n; i++) {
board[firstZero] = i;
if(isLegalPosition(board, n) && i != lastNum) {
return board;
}
}
lastNum = -1;
board[firstZero - 1] = 0;
Successor(board, n);
} else {
templast = board[n - 1];
for(int i = board[n - 1]; i < n; i++) {
board[n - 1] = i;
if(isLegalPosition(board, n) && i != board[n-1] && i != lastNum) {
return board;
}
}
lastNum = templast;
board[n - 1] = 0;
Successor(board, n);
}
} else {
if(firstZero != -1) {
if(firstZero != 0) {
for(int i = board[firstZero - 1]; i < n; i++) {
board[firstZero - 1] = i;
if(isLegalPosition(board, n) && i != board[firstZero - 1]) {
return board;
}
}
lastNum = -1;
board[firstZero - 1] = 0;
Successor(board, n);
} else {
board[0] = 1;
return board;
}
} else {
templast = board[n - 1];
for(int i = board[n - 1]; i < n; n++) {
board[n - 1] = i;
if(isLegalPosition(board, n) && i != board[n - 1] && i != templast) {
return board;
}
}
lastNum = templast;
board[n - 1] = 0;
Successor(board, n);
}
}
}
Upvotes: 1
Views: 88
Reputation: 10096
Your recursive calls don't return anything. With all warnings on, you should be seeing something about "not all control paths return a value". Change your recursive calls to
return Successor( board, n );
Upvotes: 1