java 藍橋杯 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


import  java.util.*;

public class Main
{
	static int n,count=0;
	static int map[][];
	public static void main(String args[])
	{
		Scanner cn=new Scanner(System.in);
		n=cn.nextInt();
		map=new int[n][n];
		for(int i=0;i<n;i++)
			for(int j=0;j<n;j++)
				map[i][j]=cn.nextInt();
		Put(0,2);   //假設黑皇后爲2 白皇后爲3  放了皇后的地方就用2,3表示
		System.out.println(count);
	}
	public static void Put(int t,int s)
	{
		if(t==n)
		{
			if(s==2)Put(0,3);
			else count++;
			return ;
		}
		for(int i=0;i<n;i++)
		{
			
			if(map[t][i]!=1)continue;
			if(Check(t,i,s))map[t][i]=s;
			else continue;
			Put(t+1,s);
			map[t][i]=1;   //回溯法的關鍵 
		}
		return ;
	}
	public static boolean Check(int t,int i,int s)
	{
		for(int q=t-1;q>=0;q--)
		{
			if(map[q][i]==s)return false;
		}		
		for(int q=t-1,w=i-1;q>=0&&w>=0;q--,w--)   //檢查主對角線    這行以下的還沒放  不檢查
  		{
			if(map[q][w]==s)return false;
		}
		for(int q=t-1,w=i+1;q>=0&&w<=n-1;q--,w++)
		{
			if(map[q][w]==s)return false;
		}
		return true;
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章