基础练习 2n皇后问题
时间限制:1.0s 内存限制:512.0MB
问题描述
给定一个n*n的棋盘,棋盘中有一些位置不能放皇后。现在要向棋盘中放入n个黑皇后和n个白皇后,使任意的两个黑皇后都不在同一行、同一列或同一条对角线上,任意的两个白皇后都不在同一行、同一列或同一条对角线上。问总共有多少种放法?n小于等于8。
输入格式
输入的第一行为一个整数n,表示棋盘的大小。
接下来n行,每行n个0或1的整数,如果一个整数为1,表示对应的位置可以放皇后,如果一个整数为0,表示对应的位置不可以放皇后。
接下来n行,每行n个0或1的整数,如果一个整数为1,表示对应的位置可以放皇后,如果一个整数为0,表示对应的位置不可以放皇后。
输出格式
输出一个整数,表示总共有多少种放法。
样例输入
4
1 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1
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
1 0 1 1
1 1 1 1
1 1 1 1
1 1 1 1
样例输出
示例代码:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader; public class Main {
private static int n; // n*n棋盘,n个黑皇后和n个白皇后
private static int[][] palace; //棋盘
private static int[] column_num; //记录每个皇后放的列号
private static int count; //统计方案数
private static boolean flag = false; public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
n = Integer.parseInt(br.readLine());
palace = new int[n][n];
column_num = new int[n]; for(int i = 0; i < n; i++){
String[] str = br.readLine().split(" ");
for(int j = 0; j < n; j++){
palace[i][j] = Integer.parseInt(str[j]);
}
} place(0); System.out.println(count);
}
// 放皇后
private static void place(int quee) {
if(quee == n && !flag){ //如果n个黑皇后已经放置好,将标记置为true,然后放置n个白皇后
flag = true;
place(0);
flag = false;
}else if(quee == n && flag){ //如果黑白皇后都已经放置好,则方案数加1
count++;
}else{
for(int column = 0; column < n; column++){ //遍历列
if(palace[quee][column] == 1){ //如果发现此位置为1,即可以放皇后
int temp = column_num[quee]; //先将之前放置的列号记录下来,如果此时的列位置不能放皇后,则将之前的列号返回
column_num[quee] = column;
if(judge(quee)){ //判断放置的位置与 放置好的皇后是否右冲突
palace[quee][column] = -1; //将此时的棋盘位置置为-1
place(quee+1); //然后去放下一个皇后
palace[quee][column] = 1; //若下一个皇后没有放置好,回溯后将之前的-1变为1,即此时的位置允许放皇后
}
column_num[quee] = temp; //返回列号
}
}
}
} //判断放置的位置与放置好的皇后是否有冲突
private static boolean judge(int quee) {
for(int ready = 0; ready < quee; ready++){ //用之前的皇后去检测
if(column_num[ready] == column_num[quee] || //是否在同一列
quee + column_num[quee] == ready + column_num[ready] || //是否在左对角线
quee - column_num[quee] == ready - column_num[ready]){ //是否在右对角线
return false;
}
}
return true;
}
}