Chapter 5
■
traversal: the skeleton key of algorithmiCs
94
Let’s look at the following related problem. Show that you can order the nodes in a connected graph,
v
1
,
v
2
, . . . ,
v
n
,
so that for any
i = 1 . . .
n, the subgraph over
v
1
, . . . ,
v
i
is connected. If we can show this and we can figure out how to do
the ordering, we can go through all the nodes in a connected component and know when they’re all used up.
How do we do this? Thinking inductively, we need to get from
i–1 to
i. We know that the subgraph over the
i–1
first nodes is connected. What next? Well, because there are paths between any pair of nodes, consider a node
u in the
first
i–1 nodes and a node
v in the remainder. On the path from
u to
v, consider the last node that is
in the component
we’ve built so far, as well as the first node
outside it. Let’s call them
x and
y. Clearly there must be an edge between them,
so adding
y to the nodes of our growing component keeps it connected, and we’ve shown what we set out to show.
I hope you can see how easy the resulting procedure actually is. It’s just a matter of adding nodes that are
connected to the component, and we discover such nodes by following an edge. An interesting point is that as long
as we keep connecting new nodes to our component in this way, we’re building a
tree. This tree is called a
traversal
tree and is a spanning tree of the component we’re traversing. (For a directed graph, it would span only the nodes we
could reach, of course.)
To implement this procedure, we need to keep track of these “fringe” or “frontier” nodes that are just one edge
away. If we start with a single node, the frontier will simply be its neighbors. As we start exploring, the neighbors of
newly visited nodes will form the new fringe, while those nodes we visit now fall inside it. In other words, we need
to maintain the fringe as a collection of some sort, where we can remove the nodes we visit and add their neighbors,
unless they’re already on the list or we’ve already visited them. It becomes a sort of to-do list of nodes we want to visit
but haven’t gotten around to yet. You can think of the ones we
have visited as being checked off.
For those of you who have played old-school role-playing games such as Dungeons & Dragons (or, indeed, many
of today’s video games), Figure
5-2
might help clarify these ideas. It shows a typical dungeon map.
2
Think of the rooms
(and corridors) as nodes and the doors between them as edges. There are some multiple edges (doors) here, but that’s
really not a problem. I’ve also added a “you are here” marker to the map, along with some tracks indicating how you
got there.
a
b
c
d
e
f
g
h
i
Do'stlaringiz bilan baham: