Golang | Leetcode Golang题解之第52题N皇后II

题目:

题解:

Go 复制代码
func totalNQueens(n int) (ans int) {
    columns := make([]bool, n)        // 列上是否有皇后
    diagonals1 := make([]bool, 2*n-1) // 左上到右下是否有皇后
    diagonals2 := make([]bool, 2*n-1) // 右上到左下是否有皇后
    var backtrack func(int)
    backtrack = func(row int) {
        if row == n {
            ans++
            return
        }
        for col, hasQueen := range columns {
            d1, d2 := row+n-1-col, row+col
            if hasQueen || diagonals1[d1] || diagonals2[d2] {
                continue
            }
            columns[col] = true
            diagonals1[d1] = true
            diagonals2[d2] = true
            backtrack(row + 1)
            columns[col] = false
            diagonals1[d1] = false
            diagonals2[d2] = false
        }
    }
    backtrack(0)
    return
}
相关推荐
文丑颜不良啊19 小时前
LeetCode2241~2260题目解析
java·leetcode
文丑颜不良啊20 小时前
LeetCode2321~2340题目解析
java·leetcode
利威尔xu1 天前
2026-11-08-Go-defer-panic-recover面试
面试·golang
文丑颜不良啊2 天前
LeetCode2221~2240题目解析
java·leetcode
Navigator_Z2 天前
LeetCode //C - 1317. Convert Integer to the Sum of Two No-Zero Integers
c语言·算法·leetcode
文丑颜不良啊2 天前
LeetCode2161~2180题目解析
java·leetcode
JWASX2 天前
【Go】map 源码解析 - group
后端·golang·map·源码分析
文丑颜不良啊2 天前
LeetCode2141~2160题目解析
java·leetcode
Dream it possible!2 天前
LeetCode 面试经典 150_多维动态规划_交错字符串(97_C++_中等)
算法·leetcode·面试·动态规划
心抵鹊2 天前
算法之双指针系列(一)
算法·leetcode