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

时间:2019-12-20 13:52:57

标签: ios swift recursion backtracking sudoku

我试图迅速为数独求解器实现回溯解决方案。这是我的代码:

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

运行代码时,该函数在原始电路板上返回true。但是,当我在if Solved块中打印电路板时,我注意到该函数可以解决该电路板,但是它不会返回它,而是继续调用该函数,直到将所有0值再次设为0为止。我认为该函数不会在ifsolve(board:board).isSolved部分中退出。我该怎么做才能解决这个问题?谢谢!

1 个答案:

答案 0 :(得分:0)

问题在于您不是从solve返回修改后的返回值,而是丢弃它并返回局部变量board

您应该保存递归调用的返回值,如果其isSolved属性为true,请从递归调用返回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。