I am new to algorithms and data structures, and I have tried making a depth search for a graph but depending on the parameters it sometimes throws
TypeError: graph[start] is not iterable
In the below code, the algorithm is executed twice on the same graph, but with a different end-node: the first call returns the expected result, but the second one triggers the error:
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