解题思路:
dfs
注意事项:
参考代码:import java.util.Scanner;
public class nKingM {
static int res = 0;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] rec = new int[n];//记录数组
dfsK(rec,0);
System.out.println(res);
}
private static void dfsK(int[] rec, int row) {
if (row == rec.length) {
res++;
if(res<4){
for (int i :rec){
System.out.print(i+1+" ");
}
System.out.println();
}
return;
}
for (int i = 0; i < rec.length; i++) {//列
if(check(rec,i,row)){
rec[row] = i;
dfsK(rec,row+1);
rec[row] = 0;
}
}
}
private static boolean check( int[] rec, int col,int row) {
for (int i = 0; i < row; i++) {
if (rec[i] == col||i+rec[i] == row+col || rec[i]-i == col-row) return false;
}
return true;
}
}
0.0分
1 人评分