define breadth first search code example
Example 1: breadth first search javascript
BFS(node) {
// Create a Queue and add our initial node in it
let q = new Queue(this.nodes.length);
let explored = new Set();
q.enqueue(node);
// Mark the first node as explored explored.
add(node);
// We'll continue till our queue gets empty
while (!q.isEmpty()) {
let t = q.dequeue();
// Log every element that comes out of the Queue
console.log(t);
// 1. In the edges object, we search for nodes this node is directly connected to.
// 2. We filter out the nodes that have already been explored.
// 3. Then we mark each unexplored node as explored and add it to the queue.
this.edges[t]
.filter(n => !explored.has(n))
.forEach(n => {
explored.add(n);
q.enqueue(n);
});
}
}
Example 2: breadth first search
procedure BFS(G, start_v) is
2 let Q be a queue
3 label start_v as discovered
4 Q.enqueue(start_v)
5 while Q is not empty do
6 v := Q.dequeue()
7 if v is the goal then
8 return v
9 for all edges from v to w in G.adjacentEdges(v) do
10 if w is not labeled as discovered then
11 label w as discovered
12 w.parent := v
13 Q.enqueue(w)