1.N-皇后算法
import java.util.Scanner;
public class BT_NQueens {
private int N;
private int[] queen;
private boolean done;
public BT_NQueens(int N){
this.N = N;
queen = new int[N];
done = false;
}
public void bt_NQueens(int row){
for(int col = 0;!done && col < N;col++){
if(checkPlacing(row,col)){
queen[row] = col;
if(row == N-1){
done = true;
}else{
bt_NQueens(row + 1);
}
}
}
}
public boolean checkPlacing(int row,int col){
for(int i = 0;i < row;i++){
if(queen[i] == col || Math.abs(queen[i] - col) == Math.abs(i - row)){
return false;
}
}
return true;
}
public void print(){
System.out.println(N + "-后问题:");
for(int i=0;i<N;i++){
System.out.print("P[" + (i + 1) + "]: ");
System.out.println("(" + (i + 1) + "," + (queen[i] + 1) +")");
}
}
public static void main(String[]args){
Scanner sc = new Scanner(System.in);
System.out.println("请输入N:");
int N = sc.nextInt();
sc.close();
BT_NQueens q = new BT_NQueens(N);
q.bt_NQueens(0);
q.print();
}
}
2.K-着色问题
public class BT_KColoring {
private int N;
private int K;
private int[][] matrix;
private int[] colors;
public BT_KColoring(int N,int K,int[][] matrix){
this.N = N;
this.K = K;
this.matrix = matrix;
colors = new int[N];
}
public void bt_KColoring(int v){
int c = 1;
while(colors[N - 1] == 0 && c <= K ){
colors[v] = c;
if(checkColoring(v) == -1){
if(v < N - 1){
bt_KColoring(v + 1);
}else{
break;
}
}else {
colors[v] = 0;
}
c++;
}
if(colors[N - 1] == 0 && c > K){
colors[v] = 0;
}
}
public int checkColoring(int v){
for(int u = 0;u < v;u++)
if(matrix[v][u] == 1 && colors[u] == colors[v])
return u;
return -1;
}
public void print(){
System.out.println(K + "-着色问题:");
for(int i = 0;i < N;i++){
System.out.print("C[" + (i + 1) + "]: ");
System.out.println(colors[i] + " ");
}
}
public static void main(String[]args){
int N = 6;
int K = 4;
int[][] matrix = {
{0,1,1,0,0,1},
{1,0,1,1,0,0},
{1,1,0,1,0,1},
{0,1,1,0,1,0},
{0,0,0,1,0,1},
{1,0,1,0,1,0}
};
BT_KColoring k = new BT_KColoring(N,K,matrix);
k.bt_KColoring(0);
k.print();
}
}