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

N-Queens problem. Returning array from functions c++

在尝试解决 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任何东西。启用所有警告后,您应该会看到有关 "not all control paths return a value" 的信息。将递归调用更改为

return Successor( board, n );