N皇后问题,纠结,关于回溯,总是有些迷茫,这次把N皇后问题贴出来吧,
ublic class NQueen {
private static int N=8;
private static int[] x = new int[N+1];
private static int num=0;
public static void main(String[] args) {
nQueen(N);
System.out.println(num);
}
public static void nQueen(int n) {
x[1]=0;
int k=1;
while(k>0){
x[k]=x[k]+1;
while(x[k]<=n&&(!place(k)))
x[k]=x[k]+1;
if(x[k]<=n)
if(k==n)
output(x);
else{
k=k+1;
x[k]=0;
}
else
k=k-1;
}
}
private static void output(int[] x2) {
// TODO Auto-generated method stub
for (int i = 1; i <= N; i++)
System.out.print(x2[i]+" ");
System.out.println();
num++;
}
private static boolean place(int k) {
// TODO Auto-generated method stub
int i = 1;
while (i < k) {
if ((x[i] == x[k]) || (Math.abs(x[i] - x[k]) == Math.abs(i - k)))
return false;
i = i + 1;
}
return true;
}
}