gpt4 book ai didi

c++ - N皇后问题。从函数C++返回数组

转载 作者:行者123 更新时间:2023-12-02 10:22:56 25 4
gpt4 key购买 nike

在尝试解决c++中的n-皇后问题时。我遇到了这个错误,我会得到正确的答案,但是当返回数组指针时,我最终得到的是垃圾数字而不是答案。关于这个的怪异部分是我使用递归来解决问题,并且只有在使用递归时(即使它正确地通过了递归),我才获得垃圾编号。数组在返回之前是完全正确的。

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);
}
}

}

最佳答案

您的递归调用不会返回任何内容。启用所有警告后,您应该会看到有关“并非所有控制路径都返回值”的信息。将您的递归调用更改为

return Successor( board, n );

关于c++ - N皇后问题。从函数C++返回数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59295102/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com