【问题标题】:Swift doesn't return the correct value in recursive functionSwift 在递归函数中没有返回正确的值
【发布时间】:2019-12-20 13:52:57
【问题描述】:

我试图在 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)}

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

【问题讨论】:

  • 我建议你创建一个SudokuBoard 结构来抽象[[Int]]。然后,您可以在其上创建一个 solve 方法,返回 SudokuBoard?nil(无解决方案)或已解决的板。
  • 我还建议不要在循环很容易完成的情况下使用递归。

标签: ios swift recursion backtracking sudoku


【解决方案1】:

问题是你没有从solve返回修改后的返回值,而只是丢弃它并返回局部变量board

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-21
    • 2022-11-29
    • 2021-11-07
    • 2015-08-16
    • 2018-10-10
    • 1970-01-01
    相关资源
    最近更新 更多