Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Licence CC BY-NC-ND, Thierry Parmentelat

depth-first or breadth-first

given a non-valued directed graph G, and a start vertex V, there are 2 famous algorithms to walk the graph from V

intuitively, considering for example from the following tree

Loading...

these 2 algorithms would yield the nodes in the following orders

DF browsing from v would scan (the newlines are only cosmetic)

v v1 v11 v111 v112
v12 v121 v122
v2 v21 v211 v212
v22 v221 v222

BF browsing from v would scan (ditto)

v
v1 v2
v11 v12 v21 v22
v111 v112 v121 v122 v211 v212 v221 v222

objectives

we want to write a generator that implements these 2 browsing policies from a graph and vertex.
of course, only the nodes reachable from the entry vertex will be browsed by this method

algorithms

the 2 algorithms used to perform these scans are, interestingly, very close to one another
in both cases we need a STORAGE object, where we can store() things and retrieve() them later on

FIFO / FILO

Let us consider the following 2 storage implementations:

Exercise: you may wish to factorize both into a single class...

But let’s get to it:

retrieve → 1
retrieve → 2
retrieve → 3
retrieve → 3
retrieve → 2
retrieve → 1
v

FILO = DF - depth first

FIFO = BF - breadth first

v
v2
v21
v212
v211
v22
v221
v222
v1
v11
v112
v111
v12
v122
v121
v
v1
v2
v12
v11
v22
v21
v121
v122
v111
v112
v222
v221
v211
v212

applications

being a generator, we can combine it with all the itertools and the like

for example, if we need to print every other vertex in a DF scan

v
v21
v211
v221
v1
v112
v12
v121

or skip the first 3..

v212
v211
v22
v221
v222
v1
v11
v112
v111
v12
v122
v121