51.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package main
  2. import (
  3. "strings"
  4. )
  5. func solveNQueens(n int) (solutions [][]string) {
  6. putX := make([]int, n)
  7. colLaid := make([]bool, n)
  8. mainLaid := make([]bool, 2*n) // Range of y-x is [1-n, n-1], so y-x+n -> [1, 2n-1]
  9. viceLaid := make([]bool, 2*n-1)
  10. for y, x := 0, 0; ; { // The ith queen
  11. for ; x < n; x++ {
  12. if !(colLaid[x] || mainLaid[y-x+n] || viceLaid[x+y]) {
  13. putX[y] = x
  14. colLaid[x] = true
  15. mainLaid[y-x+n] = true
  16. viceLaid[x+y] = true
  17. x = 0 // Next step
  18. y++
  19. break
  20. }
  21. }
  22. if x == n || y == n { // Not valid or finished
  23. if y == 0 { // If y is 0 and x is n, then all solutions are found
  24. return
  25. } else if y == n {
  26. solutions = append(solutions, make([]string, 0))
  27. l := len(solutions)
  28. var sb strings.Builder
  29. for i := 0; i < n; i++ {
  30. sb.Reset()
  31. for j := 0; j < n; j++ {
  32. if putX[i] == j {
  33. sb.WriteByte('Q')
  34. } else {
  35. sb.WriteByte('.')
  36. }
  37. }
  38. solutions[l-1] = append(solutions[l-1], sb.String())
  39. }
  40. }
  41. y-- // Back tracking
  42. x = putX[y]
  43. colLaid[x] = false
  44. mainLaid[y-x+n] = false
  45. viceLaid[x+y] = false
  46. x++
  47. }
  48. }
  49. }
  50. // func main() {
  51. // fmt.Println(solveNQueens(9))
  52. // }