![](/img/trans.png)
[英]Blowing the stack on purpose with CompletableFuture yielded no stack overflow?
[英]Why is the stack blowing up
我試圖發現從起始節點可到達的所有節點。
似乎從來沒有達到過基本情況,我不確定為什么。
我的代碼:
class Vertex {
public final String name;
public int found;
public Edge[] adjacencies;
public Vertex(String argName) { name = argName; found = 0;}
}
class Edge {
public final Vertex target;
public Edge(Vertex argTarget, double argWeight) { target = argTarget; weight = argWeight; }
}
ArrayList<Vertex> merge(ArrayList<Vertex> a, ArrayList<Vertex> b) {
if(a == null) return b;
if(b == null) return a;
for(int x = 0; x < a.size(); x++)
b.add(a.get(x));
return b;
}
ArrayList<Vertex> span(Vertex b) {
System.out.println("hello");
if(b.found == 1) {
return null;
}
ArrayList<Vertex> t = new ArrayList<Vertex>();
t.add(b);
b.found = 0;
if(b.adjacencies == null) return t;
for(int x = 0; x < b.adjacencies.length; x++) {
ArrayList<Vertex> result = span(b.adjacencies[x].target);
t = merge(t, result);
}
return t;
}
我收到一個堆棧溢出錯誤,似乎卡在了遞歸中,但是我不確定為什么。
注意:這是我正在運行的圖形。
Vertex v0 = new Vertex("Redvile");
Vertex v1 = new Vertex("Blueville");
Vertex v2 = new Vertex("Greenville");
Vertex v3 = new Vertex("Orangeville");
Vertex v4 = new Vertex("Purpleville");
v0.adjacencies = new Edge[]{ new Edge(v1, 5), new Edge(v2, 10), new Edge(v3, 8) };
v1.adjacencies = new Edge[]{ new Edge(v0, 5), new Edge(v2, 3), new Edge(v4, 7) };
v2.adjacencies = new Edge[]{ new Edge(v0, 10), new Edge(v1, 3) };
v3.adjacencies = new Edge[]{ new Edge(v0, 8), new Edge(v4, 2) };
v4.adjacencies = new Edge[]{ new Edge(v1, 7), new Edge(v3, 2) };
您從不會將found設置為1,只在可能是1的情況下才將其設置為0。而且,為found使用布爾值。 另外,將addAll用於ArrayLists,並返回Collections.emptyList,而不是null。
給出這個簡單的圖形:
VertexA <---------------> VertexB
頂點A跨度。 found == 0,所以繼續,將其添加到t,設置found = 0,它具有一個鄰接關系-然后調用span(vertex b)
頂點B進入跨度。 found == 0,所以繼續,將其添加到t,設置found = 0,它具有一個鄰接關系-然后調用span(vertex a)
頂點A跨度。 found == 0,所以繼續,將其添加到t,設置found = 0,它具有一個鄰接關系-然后調用span(vertex b)
等等
我認為,問題在於應該將發現設置為1,而不是0。
(將VertexA替換為“ Redville”,將VertexB替換為“ Blueville”以適合您的示例)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.