Skip to content

Commit 11bd990

Browse files
author
王俊超
committed
commit
1 parent 84f4469 commit 11bd990

File tree

2 files changed

+70
-0
lines changed

2 files changed

+70
-0
lines changed

.idea/modules.xml

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
import java.util.ArrayList;
2+
import java.util.Arrays;
3+
import java.util.List;
4+
5+
/**
6+
* @author: wangjunchao(王俊超)
7+
* @time: 2018-09-28 15:36
8+
**/
9+
public class Solution {
10+
public List<List<String>> solveNQueens(int n) {
11+
List<List<String>> result = new ArrayList<>();
12+
13+
if (n < 1) {
14+
return result;
15+
}
16+
17+
char[][] board = new char[n][];
18+
for (int i = 0; i < n; i++) {
19+
board[i] = new char[n];
20+
Arrays.fill(board[i], '.');
21+
}
22+
23+
solveNQueens(board, 0, result);
24+
return result;
25+
}
26+
27+
private void solveNQueens(char[][] board, int row, List<List<String>> result) {
28+
if (board.length == row) {
29+
List<String> list = new ArrayList<>();
30+
for (char[] chs : board) {
31+
list.add(new String(chs));
32+
}
33+
result.add(list);
34+
}
35+
36+
for (int col = 0; col < board.length; col++) {
37+
if (canPlace(board, row, col)) {
38+
board[row][col] = 'Q';
39+
solveNQueens(board, row + 1, result);
40+
board[row][col] = '.';
41+
}
42+
}
43+
}
44+
45+
private boolean canPlace(char[][] board, int row, int col) {
46+
// 检测之前的列上是否已经放过皇后
47+
for (int i = 0; i < row; ++i) {
48+
if (board[i][col] == 'Q') {
49+
return false;
50+
}
51+
}
52+
53+
// 45度角(左下角)上是否已经存在过皇后
54+
for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; --i, --j) {
55+
if (board[i][j] == 'Q') {
56+
return false;
57+
}
58+
}
59+
60+
// 135度角上(左上角)是否已经存在过皇后
61+
for (int i = row - 1, j = col + 1; i >= 0 && j < board.length; --i, ++j) {
62+
if (board[i][j] == 'Q') {
63+
return false;
64+
}
65+
}
66+
67+
return true;
68+
}
69+
}

0 commit comments

Comments
 (0)