检查一个如下的 6 x 6 的跳棋棋盘,有六个棋子被放置在棋盘上,使得每行,每列,每条对角线(包括 两条主对角线的所有对角线)上都至多有一个棋子.
上面的布局可以用序列 2 4 6 1 3 5 来描述,第 i 个数字表示在第 i 行的相应位置有一个棋子,如下: 行号 1 2 3 4 5 6 列号 2 4 6 1 3 5 这只是跳棋放置的一个解.请遍一个程序找出所有跳棋放置的解.并把它们以上面的序列方法输出. 解按字典顺序排列.请输出前 3 个解.最后一行是解的总个数. 特别注意: 对于更大的 N(棋盘大小 N x N)你的程序应当改进得更有效.不要事先计算出所有解然后 只输出,这是作弊.如果你坚持作弊,那么你登陆 USACO Training 的帐号将被无警告删除
输入格式:
一个数字 N (6 <= N <= 13) 表示棋盘是 N x N 大小的.
输出格式:
前四行为前四个解,每个解的两个数字之间用一个空格隔开.第四行只有一个数字,表示解的总数.
import java.util.Scanner;
public class Main{
static int []cols;
static int N;
static int ways;
public static void placequeen(int n) {
if( n < 1) {
return;
}
cols = new int[N];
place(0);
}
public static void place(int row) {
if(row == cols.length) {
ways++;
show();
return;
}
for(int col = 0;col < cols.length;col++) {
if(isvalid(row,col)) {
cols[row] = col;
place(row + 1);
}
}
}
public static boolean isvalid(int row,int col) {
for(int i = 0;i < row;i++) {
if(cols[i] == col) {
return false;
}
if(row - i == Math.abs(col -cols[i])){
return false;
}
}
return true;
}
public static void show() {
for(int row = 0;row < cols.length;row++) {
for(int col = 0;col < cols.length;col++) {
if(cols[row] == col) {
System.out.print(col + 1 + " ");
}
}
}
System.out.println();
}
public static void main(String []args) {
Scanner in = new Scanner(System.in);
N = in.nextInt();
placequeen(N);
System.out.print(ways);
}
}