N-Queens
Description
The N-queens puzzle is the problem of placing n queens on an n×n chessboard, and the queens can not(Any two queens can’t be in the same row, column, diagonal line).Given an integer n, return all distinct solutions to the N-queens puzzle.Each solution contains a distinct board configuration of the N-queens’ placement, where ‘Q’ and ‘.’ each indicate a queen and an empty space respectively.
public class Solution {
/*
* @param n: The number of queens
* @return: All distinct solutions
*/
public List<List<String>> solveNQueens(int n) {
// write your code here
List<List<String>> results = new LinkedList<>();
if (n <= 0) {
return results;
}
List<Integer> cols = new ArrayList<>();
helper(results, n, cols);
return results;
}
public void helper(List<List<String>> results , int n, List<Integer> cols) {
// reach solution
if (cols.size() == n) {
results.add(Draw(cols));
return;
}
for (int i = 0; i < n; i++) {
if(!isValid(cols, i)){
continue ;
}
cols.add(i) ;
helper(results , n, cols) ;
cols.remove(cols.size()-1) ;
}
}
public boolean isValid(List<Integer> cols , int i) {
// only check rows above current one
int row = cols.size() ;
for(int j =0 ; j < cols.size() ; j++){
if(i == cols.get(j)){
return false ;
}
if(row + i == j + cols.get(j)){
return false ;
}
if(row - i == j - cols.get(j)){
return false ;
}
}
return true;
}
// build solution from temporary chessboard
public List<String> Draw(List<Integer> cols) {
List<String> result = new ArrayList<>();
for (int i = 0; i < cols.size(); i++) {
StringBuilder sb = new StringBuilder() ;
for(int j = 0; j < cols.size(); j++){
sb.append(j == cols.get(i) ? 'Q' : '.') ;
}
result.add(sb.toString()) ;
}
return result;
}
}