Go实现八皇后

八皇后都成梗了,实际上就是个递归还有对角线公式。

func isNotUnderAttack(row, col, n int, rows, hills, dales []int) bool {
    res := rows[col] + hills[row - col + 2 * n] + dales[row + col]
    return res == 0
}

func backtrack(row, count, n int, rows, hills, dales []int) int {
    for col := 0; col < n; col++ {
        if isNotUnderAttack(row, col, n, rows, hills, dales) {
            rows[col] = 1
            hills[row - col + 2 * n] = 1
            dales[row + col] = 1

            if row+1 == n {
                count++
            } else {
                count = backtrack(row + 1, count, n, rows, hills, dales)
            }
            
            rows[col] = 0
            hills[row - col + 2 * n] = 0
            dales[row + col] = 0
        }
    }
    return count
}

func totalNQueens(n int) int {
    rows := make([]int, n)
    hills := make([]int, 4*n-1)
    dales := make([]int, 2*n-1)
    return backtrack(0, 0, n, rows, hills, dales)
}

的确没啥人用Go写

猜你喜欢

转载自www.cnblogs.com/CherryTab/p/12416500.html