尋找漢密爾頓迴路(java版)
package hg;
public class Hanmierdun {
//結點的個數
public int n =5;
public int b[] = new int[5];
//是否已經經過該結點
public boolean used[] = new boolean[5];
//是否已經全部走過
public boolean cc = false;
public static void main(String args[]){
int a[][]={{0,1,1,1,0},
{1,0,1,0,1},
{1,1,0,1,0},
{1,0,1,0,1},
{0,1,0,1,0}
};
Hanmierdun aa = new Hanmierdun();
aa.dfs(a, 0, 0);
}
private void dfs(int a[][],int count,int m){
//如果所有的結點都已經走過且最後一個結點和開始的結點是相通的
if(count>=this.n&&a[b[count-1]][0]==1){
//輸出經過的結點次序
for(int i=0;i<b.length;i++){
System.out.print(b[i]+1);
}
System.out.println();
cc=true;
return;
}
else{
for(int j=0;j<a[m].length;j++){
//如果聯通且未經過
if(a[m][j]==1&&used[m]==false){
//設定為已經通過
used[m] = true;
b[count] = m;
count = count+1;
dfs(a,count,j);
//設定為未通過
used[m] = false;
count = count-1;
if(cc){
cc=false;
return;
}
}
}
}
}
}