51. N-Queens

LeetCode

link
DFS, Backtracking

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
class Solution {
private void DFS(char[][] board, int colindex, List<List<String>> ans){
if(colindex==board.length){
List<String> tmp=new ArrayList();
for(char[] row:board) {
String s = new String(row);
tmp.add(s);
}
ans.add(tmp);
return;
}
for(int i=0;i<board.length;i++){
if(isValid(board,i,colindex)){
board[i][colindex]='Q';
DFS(board, colindex+1,ans);
board[i][colindex]='.';
}
}
}
private boolean isValid(char[][] board, int row, int col){
for(int i=0;i<board.length;i++){
for(int j=0;j<=col;j++){
if(board[i][j]=='Q'&&(i==row||Math.abs(row-i)==Math.abs(col-j))) return false;
}
}
return true;
}
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>> ans = new ArrayList<>();
DFS(board, 0, ans);
return ans;
}
}

0%