Skip to content

Commit 22b9cb5

Browse files
committed
0051. N-Queens
1 parent e196403 commit 22b9cb5

File tree

4 files changed

+243
-0
lines changed

4 files changed

+243
-0
lines changed

markdown/0051. N-Queens.md

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
### [51\. N-Queens](https://leetcode.com/problems/n-queens/)
2+
3+
Difficulty: **Hard**
4+
5+
6+
The _n_-queens puzzle is the problem of placing _n_ queens on an _n_×_n_ chessboard such that no two queens attack each other.
7+
8+
![](https://assets.leetcode.com/uploads/2018/10/12/8-queens.png)
9+
10+
Given an integer _n_, return all distinct solutions to the _n_-queens puzzle.
11+
12+
Each solution contains a distinct board configuration of the _n_-queens' placement, where `'Q'` and `'.'` both indicate a queen and an empty space respectively.
13+
14+
**Example:**
15+
16+
```
17+
Input: 4
18+
Output: [
19+
[".Q..", // Solution 1
20+
"...Q",
21+
"Q...",
22+
"..Q."],
23+
24+
["..Q.", // Solution 2
25+
"Q...",
26+
"...Q",
27+
".Q.."]
28+
]
29+
Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above.
30+
```
31+
32+
33+
#### Solution
34+
35+
Language: **Java**
36+
37+
```java
38+
class Solution {
39+
   public List<List<String>> solveNQueens(int n) {
40+
       List<List<String>> result = new ArrayList<>();
41+
       if (n <= 0) {
42+
           return result;
43+
      }
44+
       LinkedList<Integer> column = new LinkedList<>();
45+
       LinkedList<Integer> pie = new LinkedList<>();
46+
       LinkedList<Integer> na = new LinkedList<>();
47+
       this.DFS(column, pie, na,
48+
               0, n, result, new ArrayList<>());
49+
       return result;
50+
  }
51+
52+
   private void DFS(LinkedList<Integer> column, LinkedList<Integer> pie, LinkedList<Integer> na,
53+
                    int row, int n, List<List<String>> result, List<String> currStat) {
54+
       if (row >= n) {
55+
           result.add(currStat);
56+
           return;
57+
      }
58+
       for (int i = 0; i < n; i++) {
59+
           if (column.contains(i) || pie.contains(i + row) || na.contains(row - i)) {
60+
               continue;
61+
          }
62+
           // 记录皇后可以攻击的点
63+
           column.add(i);
64+
           pie.add(i + row);
65+
           na.add(row - i);
66+
67+
           StringBuilder stringBuilder = new StringBuilder();
68+
           for (int j = 0; j < n; j++) {
69+
               if (j == i) {
70+
                   stringBuilder.append("Q");
71+
              } else {
72+
                   stringBuilder.append(".");
73+
              }
74+
          }
75+
           this.DFS(column, pie, na, row + 1, n, result, new ArrayList<String>(currStat) {{
76+
               add(stringBuilder.toString());
77+
          }});
78+
           // 移除,便于下一次回溯
79+
           column.pollLast();
80+
           pie.pollLast();
81+
           na.pollLast();
82+
      }
83+
  }
84+
}
85+
```
86+
![pic](https://gitee.com/jacobchang/PicBed/raw/master/2019-07-23-f66Gm8.png)

src/main/java/leetcode/_51_/Main.java

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package leetcode._51_;
2+
3+
import leetcode.common.Printer;
4+
5+
import java.util.List;
6+
7+
/**
8+
* Created by zhangbo54 on 2019-03-04.
9+
*/
10+
public class Main {
11+
public static void main(String[] args) {
12+
Solution solution = new Solution();
13+
List<List<String>> lists = solution.solveNQueens(1);
14+
System.out.println(lists);
15+
}
16+
}
17+
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
package leetcode._51_;
2+
3+
import java.util.ArrayList;
4+
import java.util.LinkedList;
5+
import java.util.List;
6+
7+
class Solution {
8+
public List<List<String>> solveNQueens(int n) {
9+
List<List<String>> result = new ArrayList<>();
10+
if (n <= 0) {
11+
return result;
12+
}
13+
LinkedList<Integer> column = new LinkedList<>();
14+
LinkedList<Integer> pie = new LinkedList<>();
15+
LinkedList<Integer> na = new LinkedList<>();
16+
this.DFS(column, pie, na,
17+
0, n, result, new ArrayList<>());
18+
return result;
19+
}
20+
21+
private void DFS(LinkedList<Integer> column, LinkedList<Integer> pie, LinkedList<Integer> na,
22+
int row, int n, List<List<String>> result, List<String> currStat) {
23+
if (row >= n) {
24+
result.add(currStat);
25+
return;
26+
}
27+
for (int i = 0; i < n; i++) {
28+
if (column.contains(i) || pie.contains(i + row) || na.contains(row - i)) {
29+
continue;
30+
}
31+
// 记录皇后可以攻击的点
32+
column.add(i);
33+
pie.add(i + row);
34+
na.add(row - i);
35+
36+
StringBuilder stringBuilder = new StringBuilder();
37+
for (int j = 0; j < n; j++) {
38+
if (j == i) {
39+
stringBuilder.append("Q");
40+
} else {
41+
stringBuilder.append(".");
42+
}
43+
}
44+
this.DFS(column, pie, na, row + 1, n, result, new ArrayList<String>(currStat) {{
45+
add(stringBuilder.toString());
46+
}});
47+
// 移除,便于下一次回溯
48+
column.pollLast();
49+
pie.pollLast();
50+
na.pollLast();
51+
// currStat.remove(stringBuilder.toString());
52+
}
53+
}
54+
}
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
### [51\. N-Queens](https://leetcode.com/problems/n-queens/)
2+
3+
Difficulty: **Hard**
4+
5+
6+
The _n_-queens puzzle is the problem of placing _n_ queens on an _n_×_n_ chessboard such that no two queens attack each other.
7+
8+
![](https://assets.leetcode.com/uploads/2018/10/12/8-queens.png)
9+
10+
Given an integer _n_, return all distinct solutions to the _n_-queens puzzle.
11+
12+
Each solution contains a distinct board configuration of the _n_-queens' placement, where `'Q'` and `'.'` both indicate a queen and an empty space respectively.
13+
14+
**Example:**
15+
16+
```
17+
Input: 4
18+
Output: [
19+
[".Q..", // Solution 1
20+
"...Q",
21+
"Q...",
22+
"..Q."],
23+
24+
["..Q.", // Solution 2
25+
"Q...",
26+
"...Q",
27+
".Q.."]
28+
]
29+
Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above.
30+
```
31+
32+
33+
#### Solution
34+
35+
Language: **Java**
36+
37+
```java
38+
class Solution {
39+
   public List<List<String>> solveNQueens(int n) {
40+
       List<List<String>> result = new ArrayList<>();
41+
       if (n <= 0) {
42+
           return result;
43+
      }
44+
       LinkedList<Integer> column = new LinkedList<>();
45+
       LinkedList<Integer> pie = new LinkedList<>();
46+
       LinkedList<Integer> na = new LinkedList<>();
47+
       this.DFS(column, pie, na,
48+
               0, n, result, new ArrayList<>());
49+
       return result;
50+
  }
51+
52+
   private void DFS(LinkedList<Integer> column, LinkedList<Integer> pie, LinkedList<Integer> na,
53+
                    int row, int n, List<List<String>> result, List<String> currStat) {
54+
       if (row >= n) {
55+
           result.add(currStat);
56+
           return;
57+
      }
58+
       for (int i = 0; i < n; i++) {
59+
           if (column.contains(i) || pie.contains(i + row) || na.contains(row - i)) {
60+
               continue;
61+
          }
62+
           // 记录皇后可以攻击的点
63+
           column.add(i);
64+
           pie.add(i + row);
65+
           na.add(row - i);
66+
67+
           StringBuilder stringBuilder = new StringBuilder();
68+
           for (int j = 0; j < n; j++) {
69+
               if (j == i) {
70+
                   stringBuilder.append("Q");
71+
              } else {
72+
                   stringBuilder.append(".");
73+
              }
74+
          }
75+
           this.DFS(column, pie, na, row + 1, n, result, new ArrayList<String>(currStat) {{
76+
               add(stringBuilder.toString());
77+
          }});
78+
           // 移除,便于下一次回溯
79+
           column.pollLast();
80+
           pie.pollLast();
81+
           na.pollLast();
82+
      }
83+
  }
84+
}
85+
```
86+
![pic](https://gitee.com/jacobchang/PicBed/raw/master/2019-07-23-f66Gm8.png)

0 commit comments

Comments
 (0)