-
Notifications
You must be signed in to change notification settings - Fork 657
/
Copy pathNQueenBruteJava
63 lines (55 loc) · 1.67 KB
/
NQueenBruteJava
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
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>>();
dfs(0, board, res);
return res;
}
private boolean validate(char[][] board, int row, int col) {
int duprow = row;
int dupcol = col;
while(row >= 0 && col >= 0) {
if(board[row][col] == 'Q') return false;
row--;
col--;
}
row = duprow;
col = dupcol;
while(col >= 0) {
if(board[row][col] == 'Q') return false;
col--;
}
row = duprow;
col = dupcol;
while(col >= 0 && row < board.length) {
if(board[row][col] == 'Q') return false;
col--;
row++;
}
return true;
}
private void dfs(int col, char[][] board, List<List<String>> res) {
if(col == board.length) {
res.add(construct(board));
return;
}
for(int row = 0; row < board.length; row++) {
if(validate(board, row, col)) {
board[row][col] = 'Q';
dfs(col+1, board, res);
board[row][col] = '.';
}
}
}
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;
}
}