![]() |
#2
书生牛犊2016-09-24 09:13
|
问题描述
给定一个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

import java.util.Scanner;
/*输入的第一行为一个整数n,表示棋盘的大小。
接下来n行,每行n个0或1的整数,如果一个整数为1,
表示对应的位置可以放皇后,如果一个整数为0,表示对应的位置不可以放皇后。*/
public class Main {
@SuppressWarnings("unused")
private static int step = 0 ;
//初始化数组
@SuppressWarnings("resource")
private static void setArrays(int[][]a){
Scanner sc = new Scanner(System.in) ;
for(int i =0 ;i < a.length ;++i){
for(int j =0 ; j < a.length;++j){
a[i][j] = sc.nextInt() ;
}
}
}
//打印数组
@SuppressWarnings("unused")
private static void printArrays(int[][]a){
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a.length; j++) {
System.out.print(a[i][j]+" ");
}
System.out.println();
}
}
//判断i,j 位置是否合法
@SuppressWarnings("unused")
private static boolean legalWhiteQueen(int[][]a,final int i ,final int j) {
for(int n = 0 ;n < i ; ++n){
for(int m = 0 ; m < a.length ; ++m){
if(a[n][m] == 2){
if(Math.abs(i-n) == Math.abs(j- m) || j == m) return false;
}else continue ;
}
}
return true;
}
//判断i,j位置是否合法
@SuppressWarnings("unused")
private static boolean legalBlackQueen(int[][]a,final int i ,final int j) {
for(int n = 0 ; n < i ; n++){
for(int m = 0 ; m < a.length ;++m){
if(a[n][m] == 3){
if(Math.abs(i-n) == Math.abs(j-m) || j == m)return false;
}
}
}
return true;
}
//TODO 其次判断黑皇后
private static void blackQueen(int[][]a,int tag){
if(tag == a.length){step++;/*System.out.println("step:" +step);printArrays(a);System.out.println();*/}
else{
for(int j = 0 ; j < a.length ; ++j){
if(a[tag][j] != 2 && a[tag][j] != 0 ){
a[tag][j] = 3;
if(legalBlackQueen(a, tag, j)){
blackQueen(a, tag+1);
}
a[tag][j] = 1;
}
}
}
}
// TODO 首先判断白皇后
@SuppressWarnings("unused")
private static void whiteQueen(int[][]a,int tag){
if(tag == a.length)blackQueen(a, 0);
else{
for(int j = 0 ; j < a.length ; ++j){
if(a[tag][j] != 0){
a[tag][j] = 2;
if(legalWhiteQueen(a, tag, j)){
whiteQueen(a, tag+1);
}
a[tag][j] = 1;
}
}
}
}
@SuppressWarnings({ "unused", "resource" })
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt() ;
int[][]a = new int[n][n] ;
setArrays(a);
whiteQueen(a, 0);
System.out.println(step);
}
}
实例数据运行全部相同,但是提交出现了“运行错误”提示。请问这是为什么