题目链接:八皇后问题
java代码:
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static int n, count = 0;
public static int b[] = new int[14];
public static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
n = in.nextInt();
f(1);
System.out.println(count);
}
public static void f(int line) {
if(line>n) {
count++;
if(count>3) return;
else {
for(int i=1;i<=n;++i) {
System.out.print(b[i]);
if(i!=n) System.out.print(" ");
}
System.out.println();
return;
}
}
for(int i=1;i<=n;++i) {
if(isPut(line,i)==true) {
b[line] = i;
f(line+1);
b[line] = 0;
}
}
}
public static boolean isPut(int line, int col) {
for(int i=1;i<=line-1;++i) {
if(col==b[i]||(line-i)==(col-b[i])||(line-i)==(b[i]-col))
return false;
}
return true;
}
}
|