Repository navigation
Expand file tree
/
Copy pathNQueens.java
More file actions
56 lines (49 loc) · 1.59 KB
/
Copy pathNQueens.java
File metadata and controls
56 lines (49 loc) · 1.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
class Solution {
List<List<String>> result = new ArrayList<List<String>>();
public List<List<String>> solveNQueens(int n) {
List<String> board = new ArrayList<String>();
for(int i=0; i<n; i++) {
StringBuilder row = new StringBuilder("");
for(int j=0; j<n; j++)
row.append(".");
board.add(row.toString());
}
solve(0, board);
return result;
}
public void solve(int row, List<String> board) {
if(row == board.size()) {
result.add(new ArrayList<>(board));
return;
}
for(int j=0; j< board.size(); j++) {
if(isSafe(row,j,board)) {
StringBuilder newRow = new StringBuilder(board.get(row));
newRow.setCharAt(j, 'Q');
board.set(row, newRow.toString());
solve(row+1, board);
newRow.setCharAt(j, '.');
board.set(row, newRow.toString());
}
}
}
public boolean isSafe(int row, int col, List<String> board) {
// row-1, col
// row-1, col-1
// row-1, col+1
for(int i=row-1; i>=0; i--) {
if(board.get(i).charAt(col) == 'Q') return false;
}
for(int i=row-1, j=col-1; i>=0 && j>=0;) {
if(board.get(i).charAt(j) == 'Q') return false;
i--;
j--;
}
for(int i=row-1, j=col+1; i>=0 && j<board.size();) {
if(board.get(i).charAt(j) == 'Q') return false;
i--;
j++;
}
return true;
}
}