0
我有一個任務的問題,要求實現接口方法isHamiltonian
,我試圖通過使用遞歸來解決問題。如何檢測圖是否是哈密爾頓的
的想法是簡單地嘗試所有路徑從一個節點,如果滿足條件,只有一次
- 旅行的所有節點的路徑
我會說這是哈密爾頓語。
我嘗試了這些代碼,但它不工作
public static boolean isHamiltonian(Graph g) throws InvalidGraphException {
if (g == null || !(g instanceof GraphI) || ((GraphI) g).getDirected()) {
throw new InvalidGraphException();
}
NodeI[] nodes = (NodeI[]) g.nodes();
if (nodes.length < 3)
return false;
return isHamiltonian(nodes[0], nodes[0], new HashSet<NodeI>());
}
private static boolean isHamiltonian(NodeI start, NodeI n, HashSet<NodeI> hs) {
hs.add(n);
NodeI[] nodes = n.getReachableNeighbours();
boolean connectedWithStart = false;
for (int i = 0; i < nodes.length; i++) {
if (nodes[i].compareTo(start) == 0) {
connectedWithStart = true;
break;
}
}
if (hs.size() == n.getGraph().nodes().length && connectedWithStart) {
return true;
}
for (int i = 0; i < nodes.length; i++) {
if (!hs.contains(nodes[i]))
isHamiltonian(start, nodes[i], hs);
}
return false;
}
'不起作用'是一個非常普遍的事情要說。什麼不起作用? – 2013-02-12 10:17:10