
Title:
0316 Depth vs Breadth First Search

Description:

To get a handle on how to best find shortest paths in a graph,

it's going to help to compare a little bit between the kinds of depth first search algorithms

that we were looking at with the kinds of breadth first search algorithms

that we're going to need to look at.

So let's consider what the check_connection algorithm that we were just talking about does

if it's given this graph, G, and we ask it to check the connection between i and n.

The flow of control is when we do check_connection on i and n,

checking to see whether i and n are connected in the graph,

the way that it proceeds is it starts off at i

then visits the neighbors of i in some order.

Let's say it visits j first and then it asks, "Has j been visited so far? i has."

"Has j been visited so far?" No.

"Okay, well, let's go to j and do a mark_component from j."

It's going to consider the neighbors of j in some order.

Let's say it considers k first. "Has k been visited?" No.

"All right. Let's go mark_component on k." And so on.

So at some point, it may actually check one of the neighbors that it's already visited,

but at this point, once it's kind of heading in this direction,

it's going to continue to explore the graph this way,

and it will eventually hit n.

Essentially, the path that it followed to get to n is 1, 2, 3, 4, 5 links long,

which is not very representative of the shortest path, which in this case is just the 1 link.

So partly what's going on when you run this kind of algorithm

is it's diving deep into the graph.

It starts off at i and it just keeps digging itself deeper and deeper

and deeper and deeper and deeper.

And really what we'd like to do is kind of check in circles around i.

We start at i and check the things that are close to i before the things that are far from i.

And that's the essence of what breadth first search is going to do.