/** * Hamilton Path Detection for DAG */ public class DAGHamiltonPath { private boolean hamiltonPathPresent; private Digraph di; private KahnTopological kts; // 這裏使用Kahn算法進行拓撲排序 public DAGHamiltonPath(Digraph di, KahnTopological kts) { this.di = di; this.kts = kts; process(); } private void process() { Integer[] topoResult = kts.getResultAsArray(); // 依次檢查每一對相鄰頂點,若是兩者之間沒有路徑,則不存在哈密頓路徑 for(int i = 0; i < topoResult.length - 1; i++) { if(!hasPath(topoResult[i], topoResult[i + 1])) { hamiltonPathPresent = false; return; } } hamiltonPathPresent = true; } private boolean hasPath(int start, int end) { for(int w : di.adj(start)) { if(w == end) { return true; } } return false; } public boolean hasHamiltonPath() { return hamiltonPathPresent; } }