【发布时间】: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