-
Notifications
You must be signed in to change notification settings - Fork 656
/
Copy pathNQueenEfficientJava
47 lines (41 loc) · 1.64 KB
/
NQueenEfficientJava
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
class Solution {
public List<List<String>> solveNQueens(int n) {
char[][] board = new char[n][n];
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
board[i][j] = '.';
List<List<String>> res = new ArrayList<List<String>>();
int leftRow[] = new int[n];
int upperDiagonal[] = new int[2*n-1];
int lowerDiagonal[] = new int[2*n-1];
solve(0, board, res, leftRow, lowerDiagonal, upperDiagonal);
return res;
}
private void solve(int col, char[][] board, List<List<String>> res, int leftRow[], int lowerDiagonal[], int upperDiagonal[]) {
if(col == board.length) {
res.add(construct(board));
return;
}
for(int row = 0; row < board.length; row++) {
if(leftRow[row] == 0 && lowerDiagonal[row+col] == 0 && upperDiagonal[board.length -1 + col - row] == 0) {
board[row][col] = 'Q';
leftRow[row] = 1;
lowerDiagonal[row+col] = 1;
upperDiagonal[board.length-1 + col - row] = 1;
solve(col+1, board, res, leftRow, lowerDiagonal, upperDiagonal );
board[row][col] = '.';
leftRow[row] = 0;
lowerDiagonal[row+col] = 0;
upperDiagonal[board.length - 1 + col - row] = 0;
}
}
}
private List<String> construct(char[][] board) {
List<String> res = new LinkedList<String>();
for(int i = 0; i < board.length; i++) {
String s = new String(board[i]);
res.add(s);
}
return res;
}
}