52.go 899 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. package main
  2. func totalNQueens(n int) (total int) {
  3. putX := make([]int, n)
  4. colLaid := make([]bool, n)
  5. mainLaid := make([]bool, 2*n) // Range of y-x is [1-n, n-1], so y-x+n -> [1, 2n-1]
  6. viceLaid := make([]bool, 2*n-1)
  7. for y, x := 0, 0; ; { // The ith queen
  8. for ; x < n; x++ {
  9. if !(colLaid[x] || mainLaid[y-x+n] || viceLaid[x+y]) {
  10. putX[y] = x
  11. colLaid[x] = true
  12. mainLaid[y-x+n] = true
  13. viceLaid[x+y] = true
  14. x = 0 // Next step
  15. y++
  16. break
  17. }
  18. }
  19. if x == n || y == n { // Not valid or finished
  20. if y == 0 { // If y is 0 and x is n, then all solutions are found
  21. return
  22. } else if y == n {
  23. total++
  24. }
  25. y-- // Back tracking
  26. x = putX[y]
  27. colLaid[x] = false
  28. mainLaid[y-x+n] = false
  29. viceLaid[x+y] = false
  30. x++
  31. }
  32. }
  33. }
  34. func main() {
  35. println(totalNQueens(4))
  36. println(totalNQueens(5))
  37. println(totalNQueens(6))
  38. println(totalNQueens(7))
  39. }