When in survival (well, it's the twenty-first century, so let's say a survival video game), it's best not to wander too far from camp, otherwise you might risk getting lost. What you might do instead is wander in the area closest to camp, then as you become more comfortable with the area, increase the perimeter of space you are able to confidently explore.

In another way of saying, as the perimeter of familiarity increases, you are widening the *breadth* of your familiarity with the area.

By searching the area this way, you are subtlety conducting an algorithm known as breadth-first search.

### Assumptions

- Knowledge of <a href="https://www.devmaking.com/learn/algorithms/big-o-notation/" style="color:inherit;" target="_blank">Big-O notation</a>
- Familiarity with Graphs and Queues

# What is Breadth-First Search?

Breadth-first search (BFS) is a searching algorithm designed to traverse a tree by exploring the nearest nodes from the starting node first, then branching out to the next nearest nodes.

<div style="width:100%; margin:auto;text-align:center;"> <img src="https://www.devmaking.com/img/topics/algs/BFS_01.png" alt="BFS diagram" style="width:500px;max-width:95%;">

</div>

While breadth-first search is an algorithm for searching a graph, it is truly more of a strategy for searching a graph; it acts as a base "template" for solving similar graph problems. Using the strategy that BFS provides us with allows us to do things like find connected components and the shortest path through a graph (think GPS directions) with only slight modifications to the base code!

```
/* pseudo-code */
// Refresher of what a basic graph might look like.
class Graph {
// A list of lists for the nodes + edges.
List[] adj;
int size;
}
function BFS( Graph G, int startVert ) {
// (1).
boolean[] visited = new boolean[G.size];
// Create a new queue.
Queue q = new Queue();
visited[ startVert ] = true;
q.enqueue( startVert );
// Continue until all nodes have been visited.
while ( q is not empty ) {
int vert = q.dequeue();
// (2).
for ( int adjV in G.adj[ vert ] ) {
// (3).
if ( not visited[adjV] ) {
visited[ adjV ] = true;
q.enqueue( adjV );
}
}
}
}
```

Going over the steps in the comments:

- We want to keep an array the size of the graph to know when we've already seen a particular vertex. Without
`visited[]`

, the algorithm might get caught in an infinite loop!* - Foreshadowing to the next point, any vertices in the queue are also vertices that we have not yet visited. When a vertex
`V`

is removed from the queue, we look at every vertex that shares an edge with`V`

. - Lastly, if the vertex that shares an edge with
`V`

has not been visited yet, we mark it as visited and add it to the queue. If it has already been visited, then this step is skipped over, and the algorithm continues.

There is a similar algorithm to this that uses stacks instead of queues and it's called Depth-first search. The difference in the FIFO and LIFO (FILO) nature of the two is what differentiates them.

> *This is not true for using BFS on Trees, but on a Graph that contains a cycle, it is a real concern.

## Analysis of BFS

Performance | Memory |
---|---|

O(V + E) | O(V) |

Looking at the performance chart of BFS, you might notice that it is not the typical order of `n`

comparison. This is because the performance of BFS, and many other graph algorithms, are dependent on both the number of vertices and the number of edges.

To break down why this is the case, let's examine the algorithm deeper.

- To successfully perform BFS, the algorithm must look at every vertex once. Hence, it is directly dependent on the number of vertices,
`V`

. - When each vertex is being looped over, all of the edges that lead out of that vertex are also examined to find any unvisited nodes. In the worst case, every node in the graph could have
`V - 1`

edges, one to every other vertex. In the converse, each vertex`V`

might only have a singular edge leading from it. As you can see, this creates a lot of variance, all highly dependent on the number of edges,`E`

.

From these two points, it is clear that the performance of BFS is dependent on both the total vertices and the total edges. As a result, the performance of breadth-first search is `O(V + E)`

.

> The reason that it is not `O(V*E)`

is that not all nodes will have the same number of edges; each node has an independent amount of edges from the other nodes on the graph.

## Breadth-First Search Example

<div style="width:100%; margin:auto;text-align:center;"> <img src="https://www.devmaking.com/img/topics/algs/BFS_02.png" alt="Exploring a graph using bfs." style="max-width:95%;"> </div>

## When to use BFS

When using BFS you will find yourself using the BFS strategy more than the actual algorithm; BFS doesn't return any interesting value or modify any data in its basic implementation. Much more likely is that you would adapt the algorithm for your needs. For instance, if you were looking for a particular item in a graph, you might insert an additional check for the particular node in each iteration. BFS is very helpful for algorithms dealing with shortest distances, like Dijkstra's Algorithm. These have useful applications in GPS where you might want the fastest route to your destination.

> Often times, these applications are combined with *weighted* graphs, where the edges contain values, such as distance between each vertex.

## Further Resources

<a href="https://www.amazon.com/Algorithms-4th-Robert-Sedgewick/dp/032157351X/ref=as_li_ss_tl?_encoding=UTF8&pd_rd_i=032157351X&pd_rd_r=37c135e7-c5c4-4ed1-94ab-c2aaec60d692&pd_rd_w=PEuac&pd_rd_wg=xSJkC&pf_rd_p=1c11b7ff-9ffb-4ba6-8036-be1b0afa79bb&pf_rd_r=H3XK6W265MFMNYZ7PV3Z&psc=1&refRID=H3XK6W265MFMNYZ7PV3Z&linkCode=ll1&tag=devmaking-20&linkId=9f9600161b287607f80038c5fd85b020&language=en_US" target="_blank" style="color:#fff;border-radius:3px;background-color:#888;padding:1px 5px">Algorithms (Sedgwick)</a> An excellent resource and reference for learning algorithms in computer science.

<a href="https://www.amazon.com/Algorithms-Sanjoy-Dasgupta-ebook-dp-B006Z0QR3I/dp/B006Z0QR3I/ref=as_li_ss_tl?_encoding=UTF8&me=&qid=1566246918&linkCode=ll1&tag=devmaking-20&linkId=26b190aacb9c02d1a0815d4066f9d80e&language=en_US" target="_blank" style="color:#fff;border-radius:3px;background-color:#888;padding:1px 5px">Algorithms (Dasgupta)</a> Concise and clear overview on various types and designs of algorithms in a digestible format.

<a href="https://www.amazon.com/Introduction-Algorithms-3rd-MIT-Press/dp/0262033844/ref=as_li_ss_tl?ie=UTF8&linkCode=ll1&tag=devmaking-20&linkId=1dd5be6066b180c12926dc03e2659215&language=en_US" target="_blank" style="color:#fff;border-radius:3px;background-color:#888;padding:1px 5px">Introduction to Algorithms (CLRS)</a> An in depth and comprehensively detailed explanation of algorithms and how to design them.

<a href="https://www.amazon.com/Introduction-Graph-Theory-Dover-Mathematics/dp/0486678709/ref=as_li_ss_tl?keywords=graph+theory&qid=1566248143&s=books&sr=1-1-spons&psc=1&spLa=ZW5jcnlwdGVkUXVhbGlmaWVyPUExUVdSUTU4TjVPRzdIJmVuY3J5cHRlZElkPUEwNzM2MDIyMkIxUUdNVENLMVJFUiZlbmNyeXB0ZWRBZElkPUEwNzc2NTcyNDBEMlFGWDJRRU5XJndpZGdldE5hbWU9c3BfYXRmJmFjdGlvbj1jbGlja1JlZGlyZWN0JmRvTm90TG9nQ2xpY2s9dHJ1ZQ==&linkCode=ll1&tag=devmaking-20&linkId=3a3d02f5e5b338587f4e4e4be75fe2f2&language=en_US" target="_blank" style="color:#fff;border-radius:3px;background-color:#888;padding:1px 5px">Introduction to Graph Theory</a> An accessible, mathematic-centered approach to graph theory for new programmers and mathematicians.