Javascript 尝试实现DFS而不是BFS
我已经实现了BFS来搜索芒果卖家。不过,我现在就要尝试DFS了,但发现有点难。我尝试使用pop()和unshift()来代替,但仍然得到相同的输出。我希望看到不同的产出。如您所见,为了帮助自己,我对代码进行了注释Javascript 尝试实现DFS而不是BFS,javascript,class,depth-first-search,breadth-first-search,Javascript,Class,Depth First Search,Breadth First Search,我已经实现了BFS来搜索芒果卖家。不过,我现在就要尝试DFS了,但发现有点难。我尝试使用pop()和unshift()来代替,但仍然得到相同的输出。我希望看到不同的产出。如您所见,为了帮助自己,我对代码进行了注释 //We define a graph class Node { constructor() { //hash map this.connections = new Map() //attributes this.
//We define a graph
class Node {
constructor() {
//hash map
this.connections = new Map()
//attributes
this.attributes = new Map()
}
}
class Graph {
constructor() {
//get nodes
this.nodes = new Node()
}
//Add node
addNode(node) {
this.nodes.connections.set(node, [])
this.nodes.attributes.set(node, [])
}
addNodeAttribute(node, attribute) {
//set a node attribute
this.nodes.attributes.get(node).push(attribute)
}
//Create an edge
addEdge(source, destination) {
//if A is friend with B, b is friends with A //undirected
this.nodes.connections.get(source).push(destination)
this.nodes.connections.get(destination).push(source)
}
breadthFirstSearch(startingNode) {
let visitedNodes = []
let queue = []
visitedNodes[startingNode] = true
queue.push(startingNode)
while (queue.length > 0) {
const currentNode = queue.shift() //takes the first element
const connections = this.nodes.connections.get(currentNode)
if (this.nodes.attributes.get(currentNode) == "Mango") {
return currentNode
}
for (let node of connections) {
if(!visitedNodes[node]) { //if not visited
visitedNodes[node] = true //then true
queue.push(node) //push node
}
}
}
return "no mango sellers"
}
}
let graph = new Graph()
//Create nodes
graph.addNode("Nicolai")
graph.addNode("Alice")
graph.addNode("Claire")
graph.addNode("Peggy")
graph.addNode("Bob")
graph.addNode("Anuj")
graph.addNode("Jonny")
graph.addNode("Thom")
//selling mangoer
graph.addNodeAttribute("Thom", "Mango")
//add edeges
graph.addEdge("Nicolai", "Bob")
graph.addEdge("Nicolai", "Claire")
graph.addEdge("Nicolai", "Alice")
graph.addEdge("Alice", "Peggy")
graph.addEdge("Bob", "Peggy" )
graph.addEdge("Bob", "Anuj")
graph.addEdge("Claire", "Thom")
graph.addEdge("Claire", "Jonny")
console.log(graph.nodes.connections)
请只留下代码的相关部分。深度优先代码在哪里?这里的所有内容都是BFSOK,请尝试深度优先搜索版本,如果您有特定问题,您可以发布代码并询问。