跟n皇後是一樣的思路,不過每行要放兩個棋子。黑皇後和白皇後的棋子分開存儲就行了。
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main{
private static int n;
private static List<int[]> blacks = new ArrayList<>();
private static List<int[]> whites = new ArrayList<>();
private static int ans;
private static int[][] map;
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
n = scanner.nextInt();
map = new int[n][n];
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
map[i][j] = scanner.nextInt();
}
}
scanner.close();
dfs(0);
System.out.println(ans);
}
private static boolean isValid(int r, int c, List<int[]> queues){
if(map[r][c] == 0) return false;
for(int[] queue : queues){
int qr = queue[0];
int qc = queue[1];
if(qc == c) return false;
if(r - qr == Math.abs(c - qc)) return false;
}
return true;
}
private static void dfs(int row){
if(row == n){
ans += 1;
return;
}
for(int black = 0; black < n; black++){
if(!isValid(row, black, blacks))
continue;
for(int white = 0; white < n; white++){
if(black == white)
continue;
if(!isValid(row, white, whites))
continue;
int[] blackQueue = new int[]{row, black};
int[] whiteQueue = new int[]{row, white};
blacks.add(blackQueue);
whites.add(whiteQueue);
dfs(row + 1);
blacks.remove(blackQueue);
whites.remove(whiteQueue);
}
}
}
}