Я пытаюсь реализовать DFS в TS. Ниже приведен код, который у меня есть:
function allPathsDFSRecursive(searchSpace: Collections.Stack<Station>, goalNode: Station, paths: Collections.Set<Array<Station>>) {
const current = searchSpace.peek()
if (current.getName() == goalNode.getName()){
const path: Station[] = []
searchSpace.forEach(element => {
paths.add([element])
})
} else {
current.getNeighbours().forEach((station: Station) => {
if (!searchSpace.contains(station)) {
searchSpace.push(station)
allPathsDFSRecursive(searchSpace, goalNode, paths)
}
})
}
}
function depthFirstSearch(root: Station, goalNode: Station) {
const paths: Collections.Set<Array<Station>> = new Collections.Set()
const searchSpace: Collections.Stack<Station> = new Collections.Stack()
searchSpace.add(root)
allPathsDFSRecursive(searchSpace, goalNode, paths)
let shortest: Array<Station> = null
paths.forEach(path => {
if (shortest == null || shortest.length > path.length) {
shortest = path
}
})
return shortest
}
Однако, когда я запускаю его, единственный путь, который я получаю, это goalNode
Я что-то не так делаю в реализации?