【问题标题】:In a depth first search for a path, a "not iterable" error is thrown在深度优先搜索路径中,抛出“不可迭代”错误
【发布时间】:2022-09-24 20:27:44
【问题描述】:

我是算法和数据结构的新手,我尝试过对图形进行深度搜索,但取决于它有时会抛出的参数

TypeError:graph[start] 不可迭代

在下面的代码中,算法在同一个图上执行了两次,但使用不同的结束节点:第一次调用返回预期结果,但第二次调用触发错误:

const graph = {}
graph.a = [\'b\', \'c\']
graph.b = [\'f\']
graph.c = [\'d\', \'e\']
graph.d = [\'f\']
graph.e = [\'f\']
graph.f = [\'g\']

function depthSearch(graph, start, end) {
    if(start === end) return true
    if(start.visited) return false

    start.visited = true

    for(let neighbor of graph[start]) {
        if(!neighbor.visited) {
            let reached = depthSearch(graph, neighbor, end)
            if(reached) return true
        }
    }
    return false
}

console.log(depthSearch(graph, \'a\', \'g\')) //this works and returns true
console.log(depthSearch(graph, \'a\', \'d\')) //this causes TypeError: graph[start] is not iterable
  • \"取决于参数,它有时会抛出 TypeError: graph[start] is not iterable\".你能澄清一下吗?
  • start.visited = true - start 只是一个字母,你的意思是 graph[start].visited = true 吗?此外,没有在 graph.f 中引用的 graph.g,这似乎就是发生错误的原因。在这种情况下应该怎么办?

标签: javascript algorithm search


【解决方案1】:

发生这种情况是因为您没有定义graph.g,而"g" 是一个顶点,它被称为"f" 的邻居。

如果您不想在开始时显式添加叶节点,您可以提供一个备用值:

 graph[start] ?? []

但是,您的代码中还有另一个问题:

 start.visited

...因为start 是一个字符串原语,所以它没有那个属性,也不能得到它。我建议引入Set 来跟踪访问过的节点。将它作为参数传递,并给它一个默认值,以便depthSearch 的每个顶级调用都以一个空集开始。

不是问题,但是在两个地方检查节点是否已被访问过大了。只需在没有此检查的情况下进行递归调用,并相信递归调用会自行检测到。

const graph = {};
graph.a = ['b', 'c'];
graph.b = ['f'];
graph.c = ['d', 'e'];
graph.d = ['f'];
graph.e = ['f'];
graph.f = ['g'];

function depthSearch(graph, start, end, visited=new Set) {
    if(start === end) return true;
    if(visited.has(start)) return false;
    visited.add(start);

    for(let neighbor of graph[start] ?? []) {
        let reached = depthSearch(graph, neighbor, end, visited);
        if(reached) return true;
    }
    return false;
}

console.log(depthSearch(graph, 'a', 'g')); // true
console.log(depthSearch(graph, 'a', 'd')); // true

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-03
    • 2016-05-17
    • 1970-01-01
    相关资源
    最近更新 更多