djupet-först-sökning - Implementera DFS i TypeScript
Jag försöker implementera en DFS i TS. Nedan är koden jag har hittills:
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
}
Men när jag kör det är den enda vägen jag får goalNode
Gör jag något fel i implementeringen?