Skip to content

Commit 0571304

Browse files
aQuaaQua
aQua
authored and
aQua
committed
finish problem 51
1 parent ebfbc0e commit 0571304

File tree

3 files changed

+21
-2
lines changed

3 files changed

+21
-2
lines changed

Diff for: Algorithms/0051.n-queens/README.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -28,8 +28,9 @@ There exist two distinct solutions to the 4-queens puzzle:
2828
题目要求,在以下地方都没有其他的Queen
2929
1. 所在的行
3030
1. 所在的列
31-
1. 45度对角线上
31+
1. 两条45度对角线上
3232

33+
和前面的数独问题一样的解题思路
3334
## 总结
3435

3536

Diff for: Algorithms/0051.n-queens/n-queens.go

+15-1
Original file line numberDiff line numberDiff line change
@@ -4,23 +4,33 @@ func solveNQueens(n int) [][]string {
44
if n == 0 {
55
return [][]string{}
66
}
7+
78
cols := make([]bool, n)
9+
// 记录 '\' 方向的对角线的占用情况
810
d1 := make([]bool, 2*n)
11+
// 记录 '/' 方向的对角线的占用情况
912
d2 := make([]bool, 2*n)
13+
1014
board := make([]string, n)
15+
1116
res := [][]string{}
17+
1218
dfs(0, cols, d1, d2, board, &res)
19+
1320
return res
1421
}
1522

16-
func dfs(r int, cols []bool, d1 []bool, d2 []bool, board []string, res *[][]string) {
23+
func dfs(r int, cols, d1, d2 []bool, board []string, res *[][]string) {
24+
1725
if r == len(board) {
1826
tmp := make([]string, len(board))
1927
copy(tmp, board)
2028
*res = append(*res, tmp)
2129
return
2230
}
31+
2332
n := len(board)
33+
2434
for c := 0; c < len(board); c++ {
2535
id1 := r - c + n
2636
id2 := 2*n - r - c - 1
@@ -31,8 +41,12 @@ func dfs(r int, cols []bool, d1 []bool, d2 []bool, board []string, res *[][]stri
3141
}
3242
b[c] = 'Q'
3343
board[r] = string(b)
44+
// 标记占用
3445
cols[c], d1[id1], d2[id2] = true, true, true
46+
3547
dfs(r+1, cols, d1, d2, board, res)
48+
49+
// 解除标记
3650
cols[c], d1[id1], d2[id2] = false, false, false
3751
}
3852
}

Diff for: Algorithms/0051.n-queens/n-queens_test.go

+4
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,10 @@ func Test_Problem0051(t *testing.T) {
2828
ast := assert.New(t)
2929

3030
qs := []question{
31+
question{
32+
para{0},
33+
ans{[][]string{}},
34+
},
3135

3236
question{
3337
para{4},

0 commit comments

Comments
 (0)