算法練習普通(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.Scanner;

public class QueensProblem {
		static int a[],s[];
		static int arr[][];
		static int n;
		static int ac=0;
		static int q;
		
	public static void main(String[] args) {
		// 
		Scanner sc=new Scanner(System.in);
		n=sc.nextInt();
		a=new int[ n ];
		s=new int[ n ];
		arr=new int[ n + 1 ][ n + 1 ];
		
		for (int i = 1; i <= n; i++) 
			for (int j = 1; j <= n; j++) 
				arr[ i ][ j ]=sc.nextInt();
		
		sc.close();	
		
		// 先放黑皇后
		pa(0);
		System.out.println(q);
			
	}

	public static void pa(int m) {
		
		if( m == n ) {			
			// 放了一輪黑皇后,再放白皇后
			pas(0);
			return;
		}
		for (int i = 1; i <= n; i++) {
			// 如果是1就可以放皇后
			if(arr[ m + 1 ][ i ] != 0) {
				a[ m ] = i;		//放入一個皇后
				ac = 1;			// 1代表沒有衝突
				
				for (int j = 0; j < m; j++) {
					// 同行同列是否有衝突
					if(a[ m ] == a[ j ])
						ac = 0;
					
					// 對角線上是否有衝突
					else if(Math.abs(a[ j ] - a[ m ]) == ( m - j ))
						ac = 0;
				}
				
				if( ac == 1) 
					pa( m + 1 );
			}
		}
	}
	

	public static void pas(int m) {
		if( m == n ) {
			q++;
			return;
		}
		
		for (int i = 1; i <= n; i++) {
			if(arr[ m + 1 ][ i ] == 1 && a[ m ] != i) {
				s[ m ] = i;
				ac = 1;	
				
			for (int j = 0; j < m; j++) {
				if(s[ m ] == s[ j ])
					ac = 0;
				else if(Math.abs(s[ j ] - s[ m ]) == ( m - j ))
						ac = 0;
			}
			
			if( ac == 1 ) 
				pas( m + 1 );
			
			}
			
		}
	}
	
}

在這裏插入圖片描述

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