問題描述:
給定一個n*n的棋盤,棋盤中有一些位置不能放皇后。現在要向棋盤中放入n個黑皇后和n個白皇后,使任意的兩個黑皇后都不在同一行、同一列或同一條對角線上,任意的兩個白皇后都不在同一行、同一列或同一條對角線上。問總共有多少种放法?n小於等於8。
樣例輸入
4
1 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1
樣例輸出
2
解題思路:
八皇后問題的一個簡單變形,只要放完白皇后之後開始放黑皇后即可,若都能放解法+1
package 藍橋;
import java.util.Scanner;
public class NQueen {
static int count = 0;// 解法計數
static int[][] arry;// 棋盤
static int n;// 皇后數
public static void findQueen(int row, int color) {
if (row == n) {
// 搜尋到最後一行,即放完一種顏色的皇后了
if (color == 2) {//放完白,開始放黑
findQueen(0, 3);
} else {//黑放完了,計劃數+1,我這裏將放置形式也輸出了
count++;
print();
}
return;
}
for (int coulm = 0; coulm < n; coulm++) {
// 檢查是否可放置,標記爲自己的顏色
if (cheack(row, coulm,color)) {
arry[row][coulm] = color;
// 放置下一個皇后
findQueen(row + 1, color);
// 當下一個皇后無處可放的情況時執行,將此處的皇后清除
// 若沒有發生這種情況,將不會執行,直接通過return結束
arry[row][coulm] = 1;
}
}
}
public static void print() {
System.out.println("第" + count + "種方法:");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (arry[i][j] == 1)
System.out.print("◇");//沒有放棋子的位置
else if(arry[i][j] == 0)
System.out.print("X");//不能放棋子的位置
else if(arry[i][j] == 2)
System.out.print("○");//白皇后
else if(arry[i][j] == 3)
System.out.print("●");//黑皇后
}
System.out.println();
}
System.out.println();
}
public static boolean cheack(int a, int b, int color) {
//是否可以放置
if (arry[a][b] != 1) {
return false;
}
for (int i = 0; i < n; i++) {
// 列測試
if (arry[i][b] == color)
return false;
}
for (int i = a - 1, j = b - 1; i >= 0 & j >= 0; i--, j--) {
// 左對角線
if (arry[i][j] == color)
return false;
}
for (int i = a - 1, j = b + 1; i >= 0 & j < n; i--, j++) {
// 右對角線
if (arry[i][j] == color)
return false;
}
return true;
}
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
arry = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
arry[i][j] = sc.nextInt();
}
}
findQueen(0,2);//2白3黑
System.out.println("共" + count + "種方法");
long endTime = System.currentTimeMillis(); // 獲取結束時間
System.out.println("程序運行時間:" + (endTime - startTime) + "ms");
}
}
運行結果: