There is, actually, a simple way to prevent this script from hosing the server.
Make it follow a configurable number of links, such as 5, 1 level deep and then sleep() for a few seconds. repeat until the solution is found, or all possible nodes have been exhausted. This is much slower, but the goal is to find the path between the 2 nodes, not to crash the server in the attempt.
That having been said, I wouldn't run it either.