javascript - JavaScript 图形探索算法中的递归

标签 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)  

最佳答案

通过省略 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)
    }

}

关于javascript - JavaScript 图形探索算法中的递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4931011/

相关文章:

java - 自定义哈希算法

c++ - 检查另一个顶点是否具有相同的属性值

javascript - 如何使用对象数组创建对象

javascript - 如何将参数传递给模态弹出窗口?

javascript - 用线连接元素

algorithm - 确定一个数字的可能组合的数量以获得指定的结果

python - 如何在指数大列表中找到第 k 个最大元素?

python - 两种不同的聚类方法(通过频谱分析)和两种不同的结果......发生了什么?

events - 使用 Microsoft graph 创建事件时出错

javascript - jquery 从 title 属性获取动态生成的内容