【题目描述】
【思路】 经典搜索题n皇后
import java.util.Scanner;
class Main{
static int res, n;
static int N = 15;
static int []f = new int [N];
static boolean vis[] = new boolean[N];
public static boolean check(int x, int y){
for(int i = 0; i < x; i++)
//注意:这里是y -f[i]不是f[x] - f[i]
if( Math.abs(y - f[i]) == Math.abs( x - i ) ) return false;
return true;
}
public static void dfs(int m){
//达到叶子结点的下一层
if( m >= n) {
if( res < 3){
for(int i = 0; i < n; i++)
System.out.print(f[i] + 1 +" ");
System.out.println();
}
res ++;
return;
}
for(int i = 0; i < n; i++){
if( !vis[i] && check( m, i)){
vis[i] = true;
f[m] = i;
dfs(m + 1);
vis[i] = false;
}
}
}
public static void main(String args[]){
Scanner reader = new Scanner(System.in);
n= reader.nextInt();
dfs(0);
System.out.println(res);
}
}