问题描述
地球人都知道,在国际象棋中,后如同太阳,光芒四射,威风八面,它能控制横、坚、斜线位置。
看过清宫戏的中国人都知道,后宫乃步步惊心的险恶之地。各皇后都有自己的势力范围,但也总能找到相安无事的办法。
所有中国人都知道,皇权神圣,伴君如伴虎,触龙颜者死......
现在有一个n*n的皇宫,国王占据他所在位置及周围的共9个格子,这些格子皇后不能使用(如果国王在王宫的边上,占用的格子可能不到9个)。当然,皇后也不会攻击国王。
现在知道了国王的位置(x,y)(国王位于第x行第y列,x,y的起始行和列为1),请问,有多少种方案放置n个皇后,使她们不能互相攻击。
输入格式
一行,三个整数,皇宫的规模及表示国王的位置
输出格式
一个整数,表示放置n个皇后的方案数
样例输入
8 2 2
样例输出
10
数据规模和约定
n<=12
import java.util.Scanner;
public class Main {
public static int n;
public static int x, y;
public static int count = 0;
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
n = s.nextInt();
x = s.nextInt();
y = s.nextInt();
s.close();
int[][] chess = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
chess[i][j] = 0;
}
}
put(chess, 0);
System.out.println(count);
}
private static void put(int[][] chess, int row) {
// TODO 自动生成的方法存根
if (row == n) {
count++;
/*
* System.out.println("第"+count+"种解法:"); for(int i=0;i<n;i++) { for(int
* j=0;j<n;j++) { System.out.print(chess[i][j]+" "); } System.out.println(); }
*/
return;
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
chess[row][j] = 0;// 清除记录,防止污染棋盘
}
chess[row][i] = 1;
if (isSafety(chess, row, i)) {
put(chess, row + 1);
}
}
}
private static boolean isSafety(int[][] chess, int row, int j) {
// TODO 自动生成的方法存根
/*
* if((x==row-1||x==row+1||x==row)&&(y==j-1||y==j+1||y==j) ) { return false; }
*/
if (Math.abs(row - (x - 1)) <= 1 && Math.abs(j - (y - 1)) <= 1) {// 我们chess是从0行0列开始,所以x和y要减1,
return false;
}
int step = 1;
while (row - step >= 0) {
if (row - step >= 0 && chess[row - step][j] == 1) {
return false;
} else if (row - step >= 0 && j - step >= 0 && chess[row - step][j - step] == 1) {
return false;
} else if (row - step >= 0 && j + step < n && chess[row - step][j + step] == 1) {
return false;
}
step++;
}
return true;
}
}