2013-04-24 25 views
0

我試圖確定無限循環的來源(出現stackoverflow錯誤),在這一點上我有點瘋狂。我試圖實現一個修改後的DFS來檢測圖形中的週期。我在第11頁的示例中使用了這個示例:http://www.cs.berkeley.edu/~kamil/teaching/sp03/041403.pdf無限循環堆棧溢出 - 修改後的DFS中的檢測週期

在此實現中,0 = WHITE,1 = GRAY,2 = BLACK。我希望我缺少一些相對簡單的東西。

public boolean containsCycle() 
{ 
    for (int i=0; i<n; i++) 
    marks[i] = 0; // Initialize all to zero - unvisited 

    for (int i=0; i<n; i++) { // n = number of vertices in the graph 
    if (marks[i]==0) { 
     if (visit(i)){ 
     return true; 
     } 
    } 
    } 
    return false; 
} 

public boolean visit(int index){ 
    marks[index] = 1; // Visited 

    for (int i=0; i<n; i++){ 
     if(isArc(index,i)){ // isArc() returns true IFF there is a directed edge from index-> 
     if (marks[i]==1) 
     return true; 
     } 
     else if (marks[i]==0) { 
     if(visit(marks[i])) 
     return true; 
     } 
    } 
    marks[index] = 2; 
    return false; 
    } 
+0

什麼是N'的'的價值和它在哪兒來的? – glenatron 2013-04-24 16:07:15

+0

'n =圖中頂點的數量' – AbstractChaos 2013-04-24 16:08:10

+0

n的值是圖中頂點的數量。這是由另一個函數決定的,我已經測試並知道返回正確的n。 – user2316407 2013-04-24 16:08:24

回答

1

看來,這應該是else if (visit(i))代替else if (visit(marks[i]))

+0

我不能夠感謝你!非常感謝。 – user2316407 2013-04-24 16:44:05