N皇后问题的回溯解法:
public class NQueen {
static int[] path;
static int N;
public static void main(String[] args) {
test(8);
}
public static void test(int _N){
N=_N;
path=new int[N+1];
backTrace(1);
}
public static void backTrace(int t){
if(t>N){
for(int i=1;i<=N;i++)
System.out.print(path[i]+",");
System.out.println(";");
return;
}
else{
for(int i=1;i<=N;i++){
path[t]=i;
if(isPlace(t)){
backTrace(t+1);
}
}
}
}
public static boolean isPlace(int k){
for(int i=1;i<k;i++){
if(path[i]==path[k]||Math.abs(i-k)==Math.abs(path[i]-path[k]))return false;
}
return true;
}
}