Swift BackTracking N-queen

Swift BackTracking N-queen

我正在尝试解决 N 皇后问题。 您可以在 https://leetcode.com/problems/n-queens/.

中找到问题

对于回溯,我了解到我们可以通过三个关键来解决问题:

  1. 做出选择

  2. 约束条件

  3. 目标

所以我想到了这个解决方案:

func solveNQueens(_ n: Int) -> [[String]] {

    typealias ChessBoard = [[Int]]
    var result = Set<ChessBoard>()


    func getIndexsOfDiagonal(row:Int,column:Int) -> [(row:Int,col:Int)] {
        var indexs = [(Int,Int)]()

        var rowIndex = row
        var colIndex = column

        while rowIndex < n && colIndex < n {
            indexs.append((rowIndex,colIndex))
            rowIndex += 1
            colIndex += 1
        }

        rowIndex = row
        colIndex = column

        while rowIndex >= 0 && colIndex >= 0  {
            indexs.append((rowIndex,colIndex))
            rowIndex -= 1
            colIndex -= 1
        }

        rowIndex = row
        colIndex = column

        while rowIndex >= 0 && colIndex < n {
            indexs.append((rowIndex,colIndex))
            rowIndex -= 1
            colIndex += 1
        }

        rowIndex = row
        colIndex = column

        while rowIndex < n && colIndex >= 0 {
            indexs.append((rowIndex,colIndex))
            rowIndex += 1
            colIndex -= 1
        }
        return indexs
    }

    func placeQuees(chessboard:ChessBoard,row:Int,column:Int) ->ChessBoard {
        var newChessBorad = chessboard
        //set row
        for index in 0..<n {
            newChessBorad[row][index] = -1
        }
        //set column
        for index in 0..<n {
            newChessBorad[index][column] = -1
        }
        //set diagonal
        for index in getIndexsOfDiagonal(row:row,column:column) {
            newChessBorad[index.row][index.col] = -1
        }

        newChessBorad[row][column] = 1

        return newChessBorad
    }

    func solve(chessboard:ChessBoard, queens: Int) {

        if queens == 0 {
            //Goal
            result.insert(chessboard)
        }

        for row in 0..<n {
            for col in 0..<n {
                //Choices
                if chessboard[row][col] == 0 {
                    //Constraints
                    let new = placeQuees(chessboard: chessboard, row: row, column: col)
                    solve(chessboard: new, queens: queens - 1)
                }
            }
        }
    }

    solve(chessboard: Array(repeating: Array(repeating: 0, count: n), count: n), queens: n)


    return result.map {
        //chessboard
        [=11=].map {
            //row to string
            [=11=].reduce("") { string,value in
                if value == 1 {
                    return string + "Q"
                } else {
                    return string + "."
                }
            }
        }
    }
}

但它有时间限制。所以我想知道我的解决方案是否使用回溯?出了什么问题,我该如何改进解决方案,我们如何解决回溯问题?什么定义了回溯?

非常感谢。

你的解决方案是回溯。当它找不到可用的 space (chessboard[row][col] == 0) 来放置皇后时,它会回溯。由于它正在寻找所有可能的解决方案,因此它也会在找到解决方案并将其插入 result.

后回溯

您的解决方案只是在每次调用 solve 时尝试过多的试验位置。请注意,任何给定行上只能有一个皇后。因此,solve 可以通过在每次调用 solve 时仅尝试将皇后放在一行中来更有效地工作。在第一次调用 solve 时,尝试将皇后放在 row 0 上。然后,您将只考虑 n 个可能的展示位置,而不是 n * n。在第二次调用 solve 时,尝试将皇后放在 row 1 上。当前 row 可以计算为 n 减去剩余的皇后数或 n - queens.

通过这个细微的修改,你的代码运行得更快,并在提交到 LeetCode 时成功通过:

func solve(chessboard:ChessBoard, queens: Int) {

    if queens == 0 {
        //Goal
        result.insert(chessboard)
    }
    else {
        let row = n - queens
        for col in 0..<n {
            //Choices
            if chessboard[row][col] == 0 {
                //Constraints
                let new = placeQuees(chessboard: chessboard, row: row, column: col)
                solve(chessboard: new, queens: queens - 1)
            }
        }
    }
}