recursion in JavaScript graph exploring algorithm -


i trying explore graph here not sure wrong explore function. recursion doesn't seem working correctly; while exploring neighbours of node 0 explored 0, 1, 2 , never returns explore 3, 4, 5; why so?

explored=[] //class definition  function graph(){     this.graph=new array();     .graph[0] = [1,0,1,1,0,1]     .graph[1] = [0,1,1,1,0,0]     .graph[2] = [1,1,1,1,0,0]     .graph[3] = [1,1,1,1,1,0]     .graph[4] = [0,0,0,1,1,0]     .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)      ( i=0;i<neighbours.length;i++){         document.write('checking'+i+' node ='+node )         if(neighbours[i] ==1 && explored[i]!=1)             this.explore(i,++depth)     }  }  g = new graph() g.explore(0,0)   

by leaving out var you're setting global variables in recursive function , stepping on toes, here's corrected code

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)      (**var** i=0;i<neighbours.length;i++){         document.write('checking'+i+' node ='+node )         if(neighbours[i] ==1 && explored[i]!=1)             this.explore(i,++depth)     }  } 

Comments

Popular posts from this blog

javascript - Enclosure Memory Copies -

php - Replacing tags in braces, even nested tags, with regex -