lc-go/solutions/0/q52/solution.go
2026-01-04 14:44:06 +09:00

24 lines
716 B
Go

package q52
func findNSolutions(nQueen, row int, rows, cols, diag1, diag2 []bool) int {
solutions := 0
if row == nQueen {
return 1
}
for col := range nQueen {
// if grid[row][col] is placeable
if !rows[row] && !cols[col] && !diag1[row+col] && !diag2[row-col+nQueen] {
rows[row], cols[col], diag1[row+col], diag2[row-col+nQueen] = true, true, true, true
solutions += findNSolutions(nQueen, row+1, rows, cols, diag1, diag2)
rows[row], cols[col], diag1[row+col], diag2[row-col+nQueen] = false, false, false, false
}
}
return solutions
}
func totalNQueens(n int) int {
buf := make([]bool, 6*n)
return findNSolutions(n, 0, buf[0:n], buf[n:2*n], buf[2*n:4*n], buf[4*n:])
}
var _ = totalNQueens