问题描述
给定一个n*n的棋盘,棋盘中有一些位置不能放皇后。现在要向棋盘中放入n个黑皇后和n个白皇后,使任意的两个黑皇后都不在同一行、同一列或同一条对角线上,任意的两个白皇后都不在同一行、同一列或同一条对角线上。问总共有多少种放法?n小于等于8。
输入格式
输入的第一行为一个整数n,表示棋盘的大小。
接下来n行,每行n个0或1的整数,如果一个整数为1,表示对应的位置可以放皇后,如果一个整数为0,表示对应的位置不可以放皇后。
输出格式
输出一个整数,表示总共有多少种放法。
样例输入
4
1 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1
样例输出
2
样例输入
4
1 0 1 1
1 1 1 1
1 1 1 1
1 1 1 1
样例输出
0
Note:先确定白皇后位置,每确定一次白皇后的位置,就搜索一次黑皇后的位置
import java.util.Scanner;
public class Main {
public static int[] black_location = new int[11];
public static int[] white_location = new int[11];
public static int[][] map = new int[11][11];
public static int n,count = 0;
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
for (int i = 1; i<= n; i++) {
for (int j = 1; j<=n; j++) {
map[i][j] = sc.nextInt();
}
}
Queen_white(1);
System.out.println(count);
}
public static boolean vaild_white(int row,int column) {
for (int i = 1; i<row; i++)
if (column == white_location[i] || Math.abs(row-i) ==
Math.abs(column-white_location[i]))
return false;
return true;
}
public static boolean vaild_black(int row,int column) {
for (int i = 1; i<row; i++)
if(column == black_location[i] || Math.abs(row-i) ==
Math.abs(column - black_location[i]))
return false;
return true;
}
public static void Queen_black(int row) {
if (row == n+1) {
count++;
// return ;
}else {
for (int i = 1; i<=n; i++) {//注意黑皇后和白皇后不能放在一个位置上
//map[row][i] == 0对应的位置不可以放皇后
if (map[row][i] == 0 || i==white_location[row])
continue;
else if (vaild_black(row,i)){
black_location[row] = i;
Queen_black(row+1);
}
}
}
}
public static void Queen_white(int row) {
if (row == n+1) {
Queen_black(1);
return ;
}else {
for (int i = 1; i<=n; i++) {
if (map[row][i] == 0 )
continue;
else if (vaild_white(row,i)){
white_location[row] = i;
Queen_white(row+1);
}
}
}
}
}