8 Pledge’s Algorithm 71
“Now it gets scary! Whatever I try, nothing works. But there must be
some way out of here – after all I did get in somehow.”
Of course there is a way out of the maze. We just have to find it. So, is
there an algorithm that finds a path out of every possible maze? Even in the
dark and without any tools such as chalk or GPS?
Amazingly, such an algorithm exists!
Pledge’s algorithm
1 Set angle counter to 0;
2 repeat
3 repeat
4 Walk straight ahead;
5 until wall hit;
6 Turn right;
7 repeat
8 Follow the obstacle’s wall;
9 until angle counter = 0;
10 until exit found;
It is not sufficient to just watch the direction of one’s nose; we need to
count the turns that we make while following the walls.
For simplicity, let us assume that all corners are rectangular, as in our
examples. Then there are only left and right turns of 90 degrees each. We
count these turns as follows. For every left turn we add 1 to our counter, for
every right turn we subtract 1 from the counter (in particular, we subtract 1
for the very first turn we make when hitting a wall).
This algorithm is said to have been invented by a 12-year-old boy named
John Pledge. And it works! Not only for our examples, but in every maze!
Let’s try to prove this.
Suppose Pledge’s algorithm does not find us a way out. Then we get stuck
in a loop that will be followed on and on. Why? There are but a few points
where we may change our direction, the corners of obstacle walls, and from
every corner the first point on an obstacle seen in the initial nose direction. If
we reach one of these points twice with the same angle-counter value, the path
between both visits is repeated forever, because our behavior never changes.
Otherwise, we reach every corner at most once with the same angle-counter
value, in particular, with value 0. When all these visits have been made, we
will never again leave the current obstacle, because whenever we can, the
counter won’t be 0. Thus, our path gets cyclic.
Moreover, we can show that the loop we are following forever can have no
self-crossings. In a crossing, two straight segments of the path – let’s call them
A and B – will meet. One of them – say A – has to be a free segment; that is,