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:
[ [".Q..", // Solution 1 "...Q", "Q...", "..Q."], ["..Q.", // Solution 2 "Q...", "...Q", ".Q.."] ]
import java.util.Stack;
public class T1 {
T1(int _n) {
n = _n;
f = new int[n];
}
int n;
int[] f;
Stack<int[]> ans = new Stack<>();
public static void main(String[] args) {
T1 t = new T1(8);
t.DFS(0);
t.print();
}
void DFS(int k) {
if (k == n) {
if (chack(n)) {
int[] a = new int[n];
for (int i = 0; i < f.length; i++) {
a[i] = f[i];
}
ans.push(a);
}
} else {
for (int i = 0; i < n; i++) {
f[k] = i;
if (chack(k))
DFS(k + 1);
}
}
}
boolean chack(int l) {
for (int i = 0; i < l; i++) {
for (int j = i + 1; j < l; j++) {
if (Math.abs(f[j] - f[i]) == j - i || f[j] == f[i]) {
return false;
}
}
}
return true;
}
void print() {
int num = 1;
while (!ans.isEmpty()) {
System.out.println("============" + num + "=======");
int[] arr = ans.pop();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (arr[i] != j)
System.out.print('.');
else
System.out.print('*');
}
System.out.println();
}
num++;
}
}
}