Swift 不是 return 递归函数中的正确值

Swift doesn't return the correct value in recursive function

我试图在 swift 中为数独解算器实现回溯解决方案。这是我的代码:

func solve(board: [[Int]]) -> (isSolved: Bool, board: [[Int]]){
    var board = board
    var empty_pos: (Int, Int)
    var check_empty = findEmpty(board: board)

    if check_empty.isEmpty == false{
        return (true, board)
    }else{
        empty_pos = check_empty.pos

        for num in 1..<10{
            if isValid(board: board, num: num, pos: empty_pos){

                board[empty_pos.0][empty_pos.1] = num

                if solve(board: board).isSolved{
                    return (true, board)
                }else{
                    board[empty_pos.0][empty_pos.1] = 0
                }
            }
        }
    }
    return (false, board)}

当我运行代码时,功能return对原板是正确的。但是,当我在 if solved 块中打印电路板时,我注意到函数解决了电路板,但它没有 return 它,并继续调用该函数,直到它再次使所有 0 值变为 0。我认为该功能不会在 if solve(board: board).isSolved 部分退出。我应该怎么做才能解决这个问题?谢谢!

问题是您没有从 solve 中 returning 修改后的 return 值,而只是丢弃它并 returning 局部变量 [=12] =].

您应该从递归调用中保存 return 值,如果它的 isSolved 属性 为真,return 来自递归调用的 board调用,而不是本地变量。

func solve(board: [[Int]]) -> (isSolved: Bool, board: [[Int]]) {
    var board = board
    var emptyPos: (Int, Int)
    var checkEmpty = findEmpty(board: board)

    if !checkEmpty.isEmpty {
        return (true, board)
    } else {
        emptyPos = checkEmpty.pos

        for num in 1..<10 {
            if isValid(board: board, num: num, pos: emptyPos){

                board[emptyPos.0][emptyPos.1] = num

                let solved = solve(board: board)
                if solved.isSolved {
                    return (true, solved.board)
                } else{
                    board[emptyPos.0][emptyPos.1] = 0
                }
            }
        }
    }
    return (false, board)
}

与您的问题无关,但您应该遵守 Swift 命名约定,即变量和函数名称采用 lowerCamelCase。