題目描述:
Y9J{PKX{Q~5KR)(KTSR22LO.png
解決方法:
遞歸+回溯
先鋪上一層皇后黍檩,再鋪一層
import java.util.*;
// 2n皇后自己寫系列
public class Queen {
static int count,n;
static int[][] map;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
map = new int[n][n]; // 記得要將map實例化
// 將輸入數組值放入map
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
map[i][j] = sc.nextInt();
}
}
// 假設放置白皇后的地方放2,放置黑皇后的地方放3
put(0,2);
System.out.println(count);
}
public static void put(int t,int s){
if( t == n){ // 表示白皇后已經放完
if(s == 2) put(0,3); // 此時開始放置黑皇后
else count++; // 如果黑皇后也已經放置完,count++
return;
}
// 挨層放
for( int i = 0; i < n; i++){
if( map[t][i] != 1) continue; // 該位置不可放任何皇后 結束本次循環(huán)
if(check(t,i,s)) map[t][i] = s; // 如果該位置可以放 那么放置皇后
else continue; // 該位置不可放置 結束本次循環(huán)
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,p = i-1; q >=0 && p >= 0;q--,p--){ // 測試左對角線是否已經放置了皇后
if(map[q][p] == s) return false;
}
for(int q = t-1,p = i+1; q >= 0&& p < n;q--,p++){ // 測試右對角線是否已經放置了皇后
if(map[q][p] == s) return false;
}
return true;
}
}