forked from algorithm020/algorithm020
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution_solveNQueens.java
More file actions
86 lines (78 loc) · 2.59 KB
/
Solution_solveNQueens.java
File metadata and controls
86 lines (78 loc) · 2.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
class Solution {
private List<List<String>> result=new ArrayList();
public List<List<String>> solveNQueens(int n) {
if(n==0){
return result;
}
//初始化二维数组
char [][] con=new char[n][n];
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
con[i][j]='.';
}
}
solve(con,0);
return result;
}
private void solve(char [][] con,int row){
if(row==con.length){
//到了最后一行了
result.add(construct(con));
return;
}
//因为是n*n棋盘,所以这里列的范围用con.length也没问题,便于理解还是使用con[0].length
for(int col=0;col<con[0].length;col++){
// if(row==0){
// for(int i=0;i<con.length;i++){
// for(int j=0;j<con.length;j++){
// con[i][j]='.';
// }
// }
// }
if(valid(row,col,con)){
//因为这里还是试错的思想,所以需要保留原始值,其实这里是回溯,只是二维数组不方便回退,而创建新的
char [][]temp=copy(con);
temp[row][col]='Q';
solve(temp,row+1);
}
}
}
private boolean valid(int row,int col,char [][]chess){
//第一种情况,判断该行以上的行是否存在皇后(同一列)
for(int i=0;i<row;i++){
if(chess[i][col]=='Q'){//同一列上已存在皇后
return false;
}
}
//第二种情况,判断左上角是否已存在皇后
for(int i=row,j=col;i>=0 && j>=0;i--,j--){
if(chess[i][j]=='Q'){
return false;
}
}
//第三种情况,判断右上角是否已存在皇后
for(int i=row,j=col;i>=0 && j<chess.length;i--,j++){
if(chess[i][j]=='Q'){
return false;
}
}
return true;
}
private char[][] copy(char[][] chess) {
char[][] temp = new char[chess.length][chess[0].length];
for (int i = 0; i < chess.length; i++) {
for (int j = 0; j < chess[0].length; j++) {
temp[i][j] = chess[i][j];
}
}
return temp;
}
//把数组转为list
private List<String> construct(char[][] chess) {
List<String> path = new ArrayList<>();
for (int i = 0; i < chess.length; i++) {
path.add(new String(chess[i]));
}
return path;
}
}