2011-02-08 3 views
1

여기 그래프를 탐색하려고하지만 탐색 기능이 잘못되었는지는 확실하지 않습니다. 재귀가 제대로 작동하지 않는 것 같습니다. 노드 0의 이웃을 탐색하면서 0, 1, 2를 탐색 한 다음 3, 4, 5를 탐색하기 위해 다시 돌아 오지 않습니다. 왜 이렇게이다?JavaScript 그래프 탐색 알고리즘의 재귀 호출

당신은 재귀 함수에서 전역 변수를 설정하고 당신의 발가락에 스테핑하고 VAR을 떠나하여
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

은, 여기로, this.explore(i,++depth)는 또한 당신에게 문제를 일으킬 수있는 수정 된 코드

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

라인이다 더

을 사용하려면 recusive 통화에 증가 값을 전달뿐만 아니라 현재 범위에 깊이를 증가하는
this.explore(i, depth + 1); 

자바 스크립트로 의심 스러울 때 jslint로 코드를 확인하는 것이 좋습니다.

+0

흠, 정확히 동일하지 않을까요? 그는 실제 탐사에 대한 깊이있는 주장을 사용하지 않지만 실제로 그가 원하는 것은 this.explore (i, depth + 1)라고 생각합니다. 따라서 호출 범위에서 깊이가 증가하지 않도록하고 들여 쓰기 그 깊이에 맞을 것입니다. – Frode

+0

사실, 변경하도록 수정합니다. –