解空間結構:
子集樹
代碼:
public class MaxTuan {
// 幾個頂點
static int n;
// 頂點的鄰接矩陣
static int[][] a;
// 當前解
static int[] x;
// 當前最優解
static int[] bestx;
// 當前頂點個數
static int cn;
// 當前最優頂點個數
static int bestn;
// 初始化
public static int maxTuan(int nn,int[][] aa)
{
n = nn;
a = aa;
x = new int[n + 1];
bestx = x;
cn = 0;
bestn = 0;
backtrace(1);
return bestn;
}
public static void backtrace(int i) {
if(i > n) {
for(int j = 1;j <=n;j++) {
bestx[j] = x[j];
System.out.print(x[j] +" ");
}
System.out.println();
bestn = cn;
return;
}
else {
boolean ok = true;
for(int j = 1;j < i;j++) {
// 已入團或者與已入團的頂點沒有邊
if(x[j]==1&&a[i][j]==0) {
ok = false;
break;
}
}
// 進入左子樹
if(ok) {
x[i] = 1;
cn ++;
backtrace(i + 1);
x[i] = 0;
cn --;
}
// 進入右子樹
if(cn + n -i > bestn) {
x[i] = 0;
backtrace(i + 1);
}
}
}
public static void main(String[] args) {
int[][] a={{-1,-1,-1,-1,-1,-1},{-1,0,1,0,1,1},{-1,1,0,1,0,1},{-1,0,1,0,0,1},{-1,1,0,0,0,1},{-1,1,1,1,1,0}};//a的下標從1開始,-1的值無用
int n=5;
Maxclique m=new Maxclique();
System.out.println("圖G的最大團解向量爲:");
System.out.println("圖G的最大團頂點數爲:"+m.maxclique(n, a));
}
}
結果截圖: