接下來n行,每行n個0或1的整數,如果一個整數爲1,表示對應的位置可以放皇后,如果一個整數爲0,表示對應的位置不可以放皇后。
1 1 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
0
package com.xjj.lanqiao;
import java.util.Scanner;
//2代表黑皇后放置位置,3代表白皇后放置位置
public class Lq2_27 {
public static int n;
public int[][] a = new int[n][n]; //棋盤
public int[] book_B = new int[n]; //標記黑皇后
public int[] col_B = new int[n]; //黑列
public int[] book_w = new int[n]; //標記白皇后
public int[] col_w = new int[n]; //白列
public static int count = 0;
//白皇后深度搜索
public void dfs_W(int index_w){
if (index_w == n) {
count++;
return;
}
for(int x = 0; x < n; x++){
if (book_w[x] == 0) {
boolean flag_w = true;
if (a[index_w][x] == 1) {
for(int y = 0; y < index_w; y++){
if (Math.abs(index_w - y) == Math.abs(x - col_w[y])) {
flag_w = false;
break;
}
}
if (flag_w) {
col_w[index_w] = x;
a[index_w][x] = 3;
book_w[x] = 1;
dfs_W(index_w + 1);
book_w[x] = 0;
a[index_w][x] = 1;
}
}
}
}
}
//黑皇后深度搜索
public void dfs_B(int index_B){
//黑皇后排列完成,進行白皇后搜索
if (index_B == n ) {
dfs_W(0);
}
//對每個皇后安排位置
for(int x = 0; x < n; x++){
//如未被訪問
if (book_B[x] == 0) {
//回溯法
boolean flag = true;
if (a[index_B][x] == 1) {
for(int y = 0; y < index_B; y++){
//在對角線
if (Math.abs(index_B - y) == Math.abs(x - col_B[y])) {
flag = false;
break;
}
}
if (flag) {
col_B[index_B] = x; //列座標
a[index_B][x] = 2; //將該點標記爲黑皇后
book_B[x] = 1; //已訪問
dfs_B(index_B + 1);
book_B[x] = 0;
a[index_B][x] = 1;
}
}
}
}
}
public static void main(String[] args) {
System.out.println();
Scanner scanner = new Scanner(System.in);
n = scanner.nextInt();
Lq2_27 lq = new Lq2_27();
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
lq.a[i][j] = scanner.nextInt();
lq.dfs_B(0);
System.out.println(count);
}
}