-
Notifications
You must be signed in to change notification settings - Fork 0
/
n_queens.go
55 lines (49 loc) · 1.08 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
package main
func solveNQueens(n int) [][]string {
colUsed := make(map[int]bool)
leftCrossLineUsed := make(map[int]bool) // row + col
rightCrossLineUsed := make(map[int]bool) // row - col
colPos := make([]int, n)
ans := make([][]string, 0)
addAns := func() []string {
queens := make([]string, n)
template := make([]byte, n)
for row:= 0;row < n;row++ {
for col:= 0; col < n; col++{
if colPos[row] == col {
template[col] = 'Q'
} else {
template[col] = '.'
}
}
queens[row] = string(template)
}
return queens
}
var dfs func(row int)
dfs = func(row int) {
if row == n {
ans = append(ans, addAns())
return
}
for col := 0; col < n; col += 1 {
l := row + col
r := row - col
if colUsed[col] || leftCrossLineUsed[l] || rightCrossLineUsed[r] {
continue
}
colUsed[col] = true
leftCrossLineUsed[l] = true
rightCrossLineUsed[r] = true
colPos[row] = col
// drill down
dfs(row + 1)
// reverse
colUsed[col] = false
leftCrossLineUsed[l] = false
rightCrossLineUsed[r] = false
}
}
dfs(0)
return ans
}