Swipe to navigate through the chapters of this book
Please log in to get access to this content
To get access to this content you need the following product:
I’ve “stolen” the subtitle for this chapter from Dudley Ernest Littlewood’s The Skeleton Key of Mathematics.
If you’re not a gamer, feel free to imagine this as your office building, dream home, or whatever strikes your fancy.
I’ll be using dicts with adjacency sets as the default representation in the following, although many of the algorithms will work nicely with other representations from Chapter 2 as well. Usually, rewriting an algorithm to use a different representation isn’t too hard either.
This is the running time of all the traversal algorithms in this chapter, except (sometimes) IDDFS.
Hey, even the story of Newton and the apple is apocryphal.
Tracing your tour from a, you should end up with the node sequence a, b, c, d, e, f, g, h, d, c, i, j, i, k, i, c, b, l, b, a.
This recursive version would be harder to use if you were actually faced with a real-life maze, of course.
And just like that, a spelunker can turn troglodyte.
People seem to end up walking in circles when wandering in the wild as well. And research by the U.S. Army suggests that people prefer going south, for some reason (as long as they have their bearings). Neither strategy is particularly helpful if you’re aiming for a complete traversal, of course.
You can perform the same procedure even if your boots aren’t muddy. Just make sure to clearly mark entries and exits (say, with a piece of chalk). In this case, it’s important to make two marks when you come to an old intersection and immediately start backtracking.
In fact, in some contexts, the term backtracking is used as a synonym for recursive traversal, or depth-first search.
The dfs_topsort function can also be used to sort the nodes of a general graph by decreasing finish times, as needed when looking for strongly connected components, discussed later in this chapter.
In other words, let’s think inductively.
IDDFS isn’t completely equivalent to Ore’s method because it doesn’t mark edges as closed in the same way. Adding that kind of marking is certainly possible and would be a form of pruning, discussed later in this chapter.
On the other hand, we’ll be jumping from node to node in a manner that could not possibly be implemented in a real-life maze.
To have any memory savings, you’d have to remove the S set. Because you’d be traversing a tree, that wouldn’t cause any trouble (that is, traversal cycles).
This might seem like cheating because I’m using topological sorting on a non-DAG. The idea is just to get the nodes sorted by decreasing finish time, though, and that’s exactly what dfs_topsort does—in linear time.
Actually, walk will return a traversal tree for each strong component.
- Traversal: The Skeleton Key of Algorithmics
Magnus Lie Hetland
- Sequence number
- Chapter number
- Chapter 5