JavaScript 图形探索算法中的递归
我试图在这里探索一个图表,但我不确定探索功能出了什么问题。递归似乎无法正常工作;在探索节点 0 的邻居时,它探索了 0、1、2,然后不再返回探索 3、4、5;为什么会这样呢?
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)
I am trying to explore a graph here but I am not sure what is wrong with the explore function. The recursion doesn't seem to be working correctly; while exploring the neighbours of the node 0 it explored 0, 1, 2 and then never returns back to explore 3, 4, 5; why is that so?
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
通过省略 var ,您可以在递归函数中设置全局变量并踩到脚趾,这是更正后的代码
by leaving out var you're setting global variables in a recursive function and stepping on your toes, here's the corrected code
this.explore(i,++深度)
行也可能会给您带来问题,因为您正在增加当前范围内的深度以及传递增加的深度
递归调用的价值,
更好地使用
当对 javascript 有疑问时,使用 jslint 检查代码总是好的。
The line
this.explore(i,++depth)
may also be causing you problems, as youare incrementing depth in the current scope as well as passing the incremented
value to the recusive call,
better to use
When in doubt with javascript it is always good to check the code with jslint.