-
Notifications
You must be signed in to change notification settings - Fork 1
/
solveNQueens.go
88 lines (69 loc) · 1.63 KB
/
solveNQueens.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
79
80
81
82
83
84
85
86
87
88
package myMath
func solveNQueens(n int) [][]string {
result := [][]string{}
path := make([]int, n)
for i := 0; i < n; i++ {
path[i] = -1
}
solveNQueensRecursion(n, map[int]bool{}, map[int]bool{}, map[int]bool{}, 0, path, &result)
return result
}
func solveNQueensRecursion(n int, rowMap, diffXY, sumXY map[int]bool, col int, path []int, res *[][]string) {
// 终止条件
if col >= n {
board := generateBoard(path, n)
*res = append(*res, board)
return
}
for i := 0; i < n; i++ {
if rowMap[i] || sumXY[col+i] || diffXY[col-i] {
continue
}
rowMap[i] = true
sumXY[col+i] = true
diffXY[col-i] = true
path[col] = i
solveNQueensRecursion(n, rowMap, diffXY, sumXY, col+1, path, res)
rowMap[i] = false
sumXY[col+i] = false
diffXY[col-i] = false
path[col] = -1
}
}
func generateBoard(queens []int, n int) []string {
board := []string{}
for i := 0; i < n; i++ {
row := make([]byte, n)
for j := 0; j < n; j++ {
row[j] = '.'
}
row[queens[i]] = 'Q'
board = append(board, string(row))
}
return board
}
// N 皇后II
func solveNQueensII(n int) int {
count := 0
solveNQueensRecursionII(n, map[int]bool{}, map[int]bool{}, map[int]bool{}, 0, &count)
return count
}
func solveNQueensRecursionII(n int, rowMap, diffXY, sumXY map[int]bool, col int, count *int) {
// 终止条件
if col >= n {
*count++
return
}
for i := 0; i < n; i++ {
if rowMap[i] || sumXY[col+i] || diffXY[col-i] {
continue
}
rowMap[i] = true
sumXY[col+i] = true
diffXY[col-i] = true
solveNQueensRecursionII(n, rowMap, diffXY, sumXY, col+1, count)
rowMap[i] = false
sumXY[col+i] = false
diffXY[col-i] = false
}
}