-
Notifications
You must be signed in to change notification settings - Fork 17
/
n-queens.go
78 lines (66 loc) · 1.68 KB
/
n-queens.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package main
import (
"strings"
)
func solveNQueens(n int) [][]string {
rows, cols := n, n
rowConstraints := make([]bool, rows)
colConstraints := make([]bool, cols)
diagConstraints := make([]bool, rows + cols)
diagNegConstraints := make([]bool, rows + cols)
// Generate board
var genBoard func() [][]string
genBoard = func() [][]string {
board := [][]string{}
for row := range make([]bool, rows) {
board = append(board, []string{})
for _ = range make([]bool, cols) {
board[row] = append(board[row], ".")
}
}
return board
}
board := genBoard()
// Output array
result := [][]string{}
checkConstraints := func(row, col int) bool {
if rowConstraints[row] || colConstraints[col] {
return false
}
if diagConstraints[row + col] || diagNegConstraints[row - col + rows] {
return false
}
return true
}
setConstraints := func(row, col int) {
rowConstraints[row], colConstraints[col] = true, true
diagConstraints[row + col], diagNegConstraints[row - col + rows] = true, true
}
unsetConstraints := func(row, col int) {
rowConstraints[row], colConstraints[col] = false, false
diagConstraints[row + col], diagNegConstraints[row - col + rows] = false, false
}
var dfs func(row int)
dfs = func(row int) {
if row == rows {
curBoard := []string{}
for boardRow := range board {
curBoard = append(curBoard, strings.Join(board[boardRow], ""))
}
result = append(result, curBoard)
return
}
for col := range make([]bool, cols) {
if checkConstraints(row, col) {
setConstraints(row, col)
board[row][col] = "Q"
dfs(row + 1)
unsetConstraints(row, col)
board[row][col] = "."
}
}
return
}
dfs(0)
return result
}