51.go 666 B

1234567891011121314151617181920212223242526272829303132
  1. package main
  2. import (
  3. "fmt"
  4. )
  5. func solveNQueens(n int) [][]string {
  6. solutions := make([][]string, 0)
  7. colNum := make([]int, n)
  8. colLaid := make([]bool, n)
  9. mainLaid := make([]bool, 2*n) // Range of row-col is [1-n, n-1], so row-col+n -> [1, 2n-1]
  10. viceLaid := make([]bool, 2*n)
  11. for row := 0; row < n; row++ { // The ith queen
  12. for col := 0; col < n; col++ {
  13. idx := row - col + n
  14. if colLaid[col] || mainLaid[idx] || viceLaid[idx] {
  15. continue
  16. }
  17. colNum[row] = col
  18. colLaid[col] = true
  19. mainLaid[idx] = true
  20. viceLaid[idx] = true
  21. break
  22. }
  23. }
  24. fmt.Println(colNum)
  25. return solutions
  26. }
  27. // func main() {
  28. // fmt.Println(solveNQueens(4))
  29. // }