Suppose now you’re looking for a particular value in a graph. (We’ll demonstrate things with a tree, but the graph does not need to be.) You essentially have two ways to go about this search (for example, to solve a maze).
Let’s say you have 10 paths before you, and each is 10 steps deep. You could
either go 10 steps down #1, then maybe 10 steps down #2, then maybe 10 steps
down #3, etc., until you find what you want or exhaust all options; or 1 step
down paths 1-10, then a second step down paths 1-10, then a third step down
paths 1-10, and so on, until, again, either tou find what you want or you
exhausted all options.
If what you’re looking for is in the graph—an exit from a
maze, for example—both of these methods will find the answer. Both are
fundamental graph algorithms.
The algorithm by which you go as deep as you can, until you can’t anymore, is
called a depth-first search: it prioritizes maximum depth on a path, before
moving to another path. The alternative is the breadth-first search, by which
you explore as many paths as possible at a certain level, before going to the
next level for any of them.
Here's the pseudocode for depth-first:
procedure DFS(node, visited):
mark node as
visited
for each neighbor
in node.neighbors:
if neighbor is
not visited:
DFS(neighbor, visited)
Note that DFS() is recursive and uses a stack.
And here’s the BFS pseudocode, which, this time, is iterative and uses a queue:
procedure BFS(Graph G, start_node):
create an empty
queue Q
mark start_node as
visited
enqueue start_node
into Q
while Q is not
empty:
node = dequeue
Q
for each
neighbor in node.neighbors:
if
neighbor is not visited:
mark
neighbor as visited
enqueue neighbor into Q
No comments:
Post a Comment