Skip to content

Commit 6046579

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

File tree

3 files changed

+64
-12
lines changed

3 files changed

+64
-12
lines changed

.idea/modules.xml

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

【052未】【N-QueensII 】/【052】【N-QueensII 】.iml

Lines changed: 0 additions & 11 deletions
This file was deleted.

0 commit comments

Comments
 (0)