我遇到一個java.lang.OutOfMemoryError當我使用一個無向圖的深度優先搜索,以確定是否節點1是可達節點2。代碼如下所示。 (一些無關痛癢的細節旨在被刪除。)深度優先搜索運行到java.lang.OutOfMemoryError
//definition of nodes and edges
Set<Node> nodes = new HashSet<Node>();
Map<Node, Set<Node>> edges = new HashMap<Node, Set<Node>>();
//method to determine if node1 is reachable to node2
public boolean isReachable(int p1, MethodNode m1, ClassNode c1, int p2, MethodNode m2, ClassNode c2) {
Node node1 = new Node (p1,m1,c1);
Node node2 = new Node (p2,m2,c2);
Stack<Node> stack = new Stack<Node>();
stack.push(node1);
while(!stack.isEmpty()){
Node current = null;
current = stack.pop();
//test current node, if its child nodes contains node2, return true
//otherwise, push its child nodes into stack
for(final Node temp : edges.get(current)){
if(temp.equals(node2)){
return true;
}
else{
stack.push(temp);
}
}
}
return false;
}
我想一定是跑出來的一些內存無限通話,但我不能找到它。
爲什麼不使用dijstras最短路徑算法? – AlexWien
我只是嘗試實現DFS和BFS來熟悉Java中的Stack和Queue。 @AlexWien –