N皇后问题
import java.util.*;
public class Solution {
private int count;
private LinkedList<int[]> result = new LinkedList<>();
public int queen(int n){
int[] columns = new int[n];
recurse(n, 0, columns);
return count;
}
private void recurse(int n, int row, int[] columns){
if(row==n){
count++;
result.add(copyArray(columns));
return;
}
for(int i=0;i<n;i++){
columns[row] = i;
int j;
for(j=0;j<row;j++){
if(columns[row]==columns[j] || (row-j)==Math.abs(columns[row]-columns[j])){
break;
}
}
if(j==row){
recurse(n, row+1, columns);
}
}
}
private int[] copyArray(int[] a){
int[] b = new int[a.length];
for(int i=0;i<a.length;i++){
b[i] = a[i];
}
return b;
}
public static void main(String[] args) {
Solution solution = new Solution();
int n = solution.queen(8);
System.out.println(n);
}
}