JavaScript图形探索算法中的递归

时间:2011-02-08 08:38:20

标签: javascript algorithm graph

我正在尝试探索图表,但我不确定探索功能有什么问题。递归似乎没有正常工作;在探索节点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)  

2 个答案:

答案 0 :(得分: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)
    }

}

答案 1 :(得分:2)

this.explore(i,++depth)也可能会导致您出现问题 在当前范围内递增深度以及递增递增的深度 重复呼叫的价值,

更好用

this.explore(i, depth + 1);

如果对javascript有疑问,最好用jslint检查代码。