forked from chuyi2007/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNQueensII.java
More file actions
30 lines (28 loc) · 935 Bytes
/
NQueensII.java
File metadata and controls
30 lines (28 loc) · 935 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
public class Solution {
public int totalNQueens(int n) {
// Start typing your Java solution below
// DO NOT write main() function
int[] board = new int[n];
return totalNQueens(0, board);
}
public int totalNQueens(int index, int[] board){
if(index == board.length)
return 1;
else{
int total = 0;
for(int i = 0; i < board.length; ++i){
if(checkBoard(board, index, i)){
board[index] = i;
total += totalNQueens(index + 1, board);
}
}
return total;
}
}
public boolean checkBoard(int[] board, int index, int val){
for(int i = 0; i < index; ++i)
if(board[i] == val || Math.abs(i - index) == Math.abs(board[i] - val))
return false;
return true;
}
}