2011-02-08 21 views
1

我想在這裏探索一個圖,但我不確定探索函數有什麼問題。遞歸似乎沒有正常工作;當探索節點0的鄰居時,探索0,1,2,然後再回到探索3,4,5;爲什麼?在JavaScript圖形探索算法中的遞歸

explored=[] 
//class definition 
function graph(){ 
    this.graph=new Array(); 
    this .graph[0] = [1,0,1,1,0,1] 
    this .graph[1] = [0,1,1,1,0,0] 
    this .graph[2] = [1,1,1,1,0,0] 
    this .graph[3] = [1,1,1,1,1,0] 
    this .graph[4] = [0,0,0,1,1,0] 
    this .graph[5] = [1,0,0,0,0,0] 

    this.explore = explore 

} 

function explore(node,depth){ 

    explored[node]=1 
    document.write('<br>') 
    for(x=0;x<depth;x++) 
     document.write('-') 
    document.write(node+'<br>') 
    neighbours=this.graph[node] 

    document.write('exploring '+node +' neighbours' + neighbours +'explored = '+explored) 

    for (i=0;i<neighbours.length;i++){ 
     document.write('checking'+i+' node is ='+node) 
     if(neighbours[i] ==1 && explored[i]!=1) 
      this.explore(i,++depth) 
    } 

} 

g = new graph() 
g.explore(0,0) 
+1

通過不使用var您已將x和i都設置爲全局變量。 – generalhenry 2011-02-08 08:49:05

+1

@generalhenry你應該讓它成爲答案,所以他可以接受它..如果沒有,我會做.. mohowhah..mwhahahaha! – Frode 2011-02-08 09:15:03

回答

4

留下了VAR你在一個遞歸函數設置全局變量,踩着你的腳趾,這裏的更正後的代碼

function explore(node,depth){ 

    explored[node]=1 
    document.write('<br>') 
    for(**var** x=0;x<depth;x++) 
     document.write('-') 
    document.write(node+'<br>') 
    **var** neighbours=this.graph[node] 

    document.write('exploring '+node +' neighbours' + neighbours +'explored = '+explored) 

    for (**var** i=0;i<neighbours.length;i++){ 
     document.write('checking'+i+' node is ='+node) 
     if(neighbours[i] ==1 && explored[i]!=1) 
      this.explore(i,++depth) 
    } 

} 
2

this.explore(i,++depth)也可導致您的問題,因爲你 在當前範圍遞增深度以及遞增 值傳遞給recusive呼叫,

最好使用

this.explore(i, depth + 1); 

如果對javascript有疑問,用jslint檢查代碼總是很好。