i have implemented BFS to search for a mango seller. However i am about to try it with DFS now - but find it a bit hard. I have tried to to use pop() and unshift() instead, but i still get the same output. I was hoping to see different output. As you can see, i have commented the code, in order to help myself.
//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)