The Maze
Welcome to the final project! The dog has ended up in a hedge maze. The editor holds the program from the Conditions lesson, which reliably took the dog along every winding path. Run it and watch the first map.
The dog walks back and forth and never gets to the goal. Why? On a winding path, there was only one way to go on from every place. A maze, however, has junctions. At a junction, the program from the Conditions lesson always goes straight ahead, so it never turns into a side passage. A program that works on one set of data can behave quite differently on another. That's why programs are tested on inputs that are as varied as possible.
There's a simple and famous algorithm for mazes: the right-hand rule. Put your right hand on a wall of the maze and never take it off. If you keep walking along the wall, you'll get to the goal in every maze whose walls are all connected. The mazes in this course are like that.
The dog has no hands, but it can do the same with blocks you know. On every pass through the loop, the dog does three things:
- It turns right, toward the wall on its right:
Turn right ↻. - It turns left for as long as there's no path ahead:
Repeat whilenotpath aheadwithTurn left ↺inside. - It takes a step:
Move forward.
Try it in your head. Where there's a path to the right, the first turn is all it takes, and the dog walks into the side passage. In a straight corridor, the first turn leaves the dog facing the hedge, so it turns left once, back the way it was going, and walks on. If the way ahead is blocked too, it turns left once more, and in a dead end, it turns all the way around. So the dog always takes the way furthest to the right, just as your hand on the wall would. When you run the program, you'll see the dog look right on every tile, as if it were feeling for the wall.
You know turning until there's a path ahead from the Not lesson. Put the three parts into the Repeat until at the goal loop, in place of the old decisions.
Instructions
- 1
Change the program so that the dog follows the right-hand rule and gets to the goal on all three maps.