简体   繁体   English

Swift 在递归函数中没有返回正确的值

[英]Swift doesn't return the correct value in recursive function

I tried to implement backtracking solution for a sudoku solver in swift.我试图在 swift 中为数独求解器实现回溯解决方案。 This is my code:这是我的代码:

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

When I run the code, the function returns true with the original board.当我运行代码时,该函数对原始板返回 true。 However, when I print the board in the if solved block, I noticed that function solves the board, but it doesn't return it, and continues to call the function until it makes all of the 0 values 0 again.但是,当我在 if 解决块中打印板时,我注意到该函数解决了板,但它没有返回它,并继续调用该函数,直到它再次使所有 0 值变为 0。 I think the function doesn't quit in the if solve(board: board).isSolved part.我认为该功能不会在 if solve(board: board).isSolved 部分退出。 What should I do to solve this?我该怎么做才能解决这个问题? Thank you!谢谢!

The issue is that you are not returning the modified return value from solve , but just discarding it and returning the local variable board .问题是您没有从solve返回修改后的返回值,而只是丢弃它并返回局部变量board

You should be saving the return value from the recursive call and if its isSolved property is true, return the board from the recursive call, not the local var.您应该保存递归调用的返回值,如果它的isSolved属性为真,则从递归调用中返回board ,而不是本地isSolved

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

Unrelated to your question, but you should be conforming to the Swift naming convention, which is lowerCamelCase for variable and function names.与您的问题无关,但您应该遵守 Swift 命名约定,即变量和函数名称的小写字母。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM