Skip to content

Commit d86a9f7

Browse files
committed
回溯: n皇后
Change-Id: If53b9de68fd91f75099dcc90d315109557c156ab
1 parent b759223 commit d86a9f7

File tree

1 file changed

+85
-0
lines changed

1 file changed

+85
-0
lines changed

go/leetcode/52.N皇后 II.go

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
/*
2+
* @lc app=leetcode.cn id=52 lang=golang
3+
*
4+
* [52] N皇后 II
5+
*
6+
* https://leetcode-cn.com/problems/n-queens-ii/description/
7+
*
8+
* algorithms
9+
* Hard (75.15%)
10+
* Likes: 71
11+
* Dislikes: 0
12+
* Total Accepted: 9.6K
13+
* Total Submissions: 12.7K
14+
* Testcase Example: '4'
15+
*
16+
* n 皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。
17+
*
18+
*
19+
*
20+
* 上图为 8 皇后问题的一种解法。
21+
*
22+
* 给定一个整数 n,返回 n 皇后不同的解决方案的数量。
23+
*
24+
* 示例:
25+
*
26+
* 输入: 4
27+
* 输出: 2
28+
* 解释: 4 皇后问题存在如下两个不同的解法。
29+
* [
30+
* [".Q..",  // 解法 1
31+
* "...Q",
32+
* "Q...",
33+
* "..Q."],
34+
*
35+
* ["..Q.",  // 解法 2
36+
* "Q...",
37+
* "...Q",
38+
* ".Q.."]
39+
* ]
40+
*
41+
*
42+
*/
43+
func totalNQueens(n int) int {
44+
rect := make([][]int, n) // 棋盘
45+
for i := 0; i < n; i++ {
46+
rect[i] = make([]int, n)
47+
}
48+
res := 0
49+
dfs(0, &rect, &res)
50+
return res
51+
}
52+
53+
func dfs(row int, rect *[][]int, res *int) {
54+
if row >= len(*rect) {
55+
*res++
56+
return
57+
}
58+
for i := 0; i < len(*rect); i++ {
59+
if isValid(rect, row, i) {
60+
(*rect)[row][i] = 1
61+
dfs(row+1, rect, res)
62+
(*rect)[row][i] = 0
63+
}
64+
}
65+
}
66+
67+
func isValid(rect *[][]int, row int, col int) bool {
68+
for i := 0; i < row; i++ {
69+
if (*rect)[i][col] == 1 {
70+
return false
71+
}
72+
}
73+
for i, j := row-1, col-1; i >= 0 && j >= 0; i, j = i-1, j-1 {
74+
if (*rect)[i][j] == 1 {
75+
return false
76+
}
77+
}
78+
for i, j := row-1, col+1; i >= 0 && j < len(*rect); i, j = i-1, j+1 {
79+
if (*rect)[i][j] == 1 {
80+
return false
81+
}
82+
}
83+
return true
84+
}
85+

0 commit comments

Comments
 (0)