L52. N-Queens II
dfs
Problem:
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.

Given an integer n, return the number of distinct solutions to the n-queens puzzle.
Example:
Input: 4
Output: 2
Explanation: There are two distinct solutions to the 4-queens puzzle as shown below.
[
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."],
["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]
Solution:
public int totalQueens(int n){
if(n <= 1) return n;
char[][] board = new char[n][n];
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
char[i][j] = '.';
}
}
int count = new int[1];
dfs(board, count, n, 0);
return count[0];
}
privat void dfs(char[][] board, int[] count, int n, int colIndex){
if(colIndex == n){
count[0]++;
return;
}
for(int i = 0; i < n; i++){
if(isValid(board, i, colIndex)){
board[i][colIndex] = 'Q';
dfs(board, count, n, colIndex+1);
board[i][colIndex] = '.';
}
}
}
private boolean isValid(char[][] board, int x, int y){
for(int i = 0; i < board.length; i++){
for(int j = 0; j < y; j++){
if(board[i][j] == 'Q' && (x == i || Math.abs(x-i) == Math.abs(y-j))){
return false;
}
}
}
return true;
}
Last updated
Was this helpful?