N-Queens
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 all distinct solutions to the n-queens puzzle.
Each solution contains a distinct board configuration of the n-queens' placement, where 'Q'
and '.'
both indicate a queen and an empty space respectively.
For example,
There exist two distinct solutions to the 4-queens puzzle:
Solution:
public class Solution {
public ArrayList<String[]> result;
public ArrayList<String[]> solveNQueens(int n) {
int[] path = new int[n];
result = new ArrayList<String[]> ();
dfs(path, 0);
return result;
}
public void dfs(int[] path, int level){
int n = path.length;
if (level == n) {
print(path);
return;
}
for(int i = 0; i < n; i++){
path[level] = i;
if (!isOK(path,level)) continue;
dfs(path, level + 1);
}
}
public boolean isOK(int[] path, int level){
int n = path.length;
boolean[] check = new boolean[n];
for(int i = 0; i < level; i++){
check[path[i]] = true;
if (path[i] + (level - i) < n) check[path[i] + (level - i)] = true;
if (path[i] - (level - i) >= 0) check[path[i] - (level - i)] = true;
}
return check[path[level]] == false;
}
public void print(int[]path){
int n = path.length;
String [] s = new String[n];
for(int i = 0; i < n; i++){
s[i] = "";
for(int j = 0; j < n; j++){
if (path[i] != j) s[i] = s[i] + ".";
else s[i] = s[i] + "Q";
}
}
result.add(s);
}
}