2011-02-08 11 views
1

ここでグラフを探索しようとしていますが、私は探索機能に何が問題なのかよく分かりません。再帰は正しく機能していないようです。ノード0の近傍を探索している間に、0,1,2を探索し、その後3,4,5を探索することは決して戻らない。どうしてこんなことに?あなたは再帰関数でグローバル変数を設定し、あなたのつま先を踏んでいるVARを除外することにより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

+1

@generalhenryあなたは答える必要があるので、彼はそれを受け入れることができます..もしそうでなければ、私はそれを行うでしょう。mohowhah ... mwhahahaha! – Frode

+0

また隣人 – generalhenry

答えて

4

は、ここで修正されたコード

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を使ってコードをチェックすることをお勧めします。

+0

うーん、それはまったく同等でしょうか?彼は実際の探査に深度議論を使用しないが、彼が実際に望んでいるのは、「this.explore(i、depth + 1)」だと思う - それで、呼び出しのスコープで深さが増えないようにする。その深さに対して正しいままです。 – Frode

+0

true、編集して変更します –

関連する問題