-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnQueen.java
More file actions
34 lines (30 loc) · 750 Bytes
/
nQueen.java
File metadata and controls
34 lines (30 loc) · 750 Bytes
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
//非常巧妙
public class nQueen {
int n;
int count;
int[] board;
public int Nqueen (int n) {
this.n = n;
this.count = 0;
this.board = new int[n];
backtrack(0);
return count;
}
public void backtrack(int row){
if(row == n){
count++;
return;}
for(int col = 0; col < n; col++){
if(check(col, row)){
board[row] = col;
backtrack(row+1);
}
}
}
public boolean check(int col, int row){
for(int i = 0; i < row; i++){
if(board[i] == col || Math.abs(row - i) == Math.abs(board[i] - col))
return false;
}return true;
}
}