2n皇后

问题描述
  给定一个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);
				}
			}
		}
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值