Skip to content

Commit 919c18e

Browse files
committed
回溯法: n皇后
Change-Id: I9922d5cefc340f1fdf7037c764a3b7f6b9a3daea
1 parent 00316a7 commit 919c18e

File tree

1 file changed

+102
-0
lines changed

1 file changed

+102
-0
lines changed

go/leetcode/51.N皇后.go

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
/*
2+
* @lc app=leetcode.cn id=51 lang=golang
3+
*
4+
* [51] N皇后
5+
*
6+
* https://leetcode-cn.com/problems/n-queens/description/
7+
*
8+
* algorithms
9+
* Hard (64.97%)
10+
* Likes: 232
11+
* Dislikes: 0
12+
* Total Accepted: 14.9K
13+
* Total Submissions: 22.7K
14+
* Testcase Example: '4'
15+
*
16+
* n 皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。
17+
*
18+
*
19+
*
20+
* 上图为 8 皇后问题的一种解法。
21+
*
22+
* 给定一个整数 n,返回所有不同的 n 皇后问题的解决方案。
23+
*
24+
* 每一种解法包含一个明确的 n 皇后问题的棋子放置方案,该方案中 'Q' 和 '.' 分别代表了皇后和空位。
25+
*
26+
* 示例:
27+
*
28+
* 输入: 4
29+
* 输出: [
30+
* ⁠[".Q..", // 解法 1
31+
* ⁠ "...Q",
32+
* ⁠ "Q...",
33+
* ⁠ "..Q."],
34+
*
35+
* ⁠["..Q.", // 解法 2
36+
* ⁠ "Q...",
37+
* ⁠ "...Q",
38+
* ⁠ ".Q.."]
39+
* ]
40+
* 解释: 4 皇后问题存在两个不同的解法。
41+
*
42+
*
43+
*/
44+
45+
// 几点性质
46+
// 1. 必定是每行一个皇后
47+
// 2. 必定是每列一个皇后
48+
func solveNQueens(n int) [][]string {
49+
rect := make([][]string, n) // 棋盘
50+
for i := 0; i < n; i++ {
51+
rect[i] = make([]string, n)
52+
for j := 0; j < n; j++ {
53+
rect[i][j] = "."
54+
}
55+
}
56+
res := [][]string{}
57+
dfs(&rect, 0, &res)
58+
return res
59+
}
60+
61+
func dfs(rect *[][]string, row int, res *[][]string) {
62+
if row >= len(*rect) {
63+
// 输出一个解
64+
ret := []string{}
65+
for _, row := range (*rect) {
66+
str := ""
67+
for _, col := range row {
68+
str += string(col)
69+
}
70+
ret = append(ret, str)
71+
}
72+
*res = append(*res, ret)
73+
return
74+
}
75+
for i := 0; i < len(*rect); i++ { // 试探各个列
76+
if isValid(rect, row, i) {
77+
(*rect)[row][i] = "Q"
78+
dfs(rect, row+1, res)
79+
(*rect)[row][i] = "."
80+
}
81+
}
82+
}
83+
84+
func isValid(rect *[][]string, row int, col int) bool {
85+
for i := 0; i < row; i++ {
86+
if (*rect)[i][col] == "Q" {
87+
return false
88+
}
89+
}
90+
for i, j := row - 1, col - 1; i >= 0 && j >= 0; i, j = i-1, j-1 {
91+
if (*rect)[i][j] == "Q" {
92+
return false
93+
}
94+
}
95+
for i, j := row - 1, col + 1; i >= 0 && j < len(*rect); i, j = i-1, j+1 {
96+
if (*rect)[i][j] == "Q" {
97+
return false
98+
}
99+
}
100+
return true
101+
}
102+

0 commit comments

Comments
 (0)