Let's run through this idea with the sample maze from earlier, repeated here:
.# .C H#
Harry begins at (2, 0) just like before, and we recursively call solve(1, 0) and solve(0, 0) like before. We again reach a dead-end at (0, 0), but instead of returning failure, we return the string "X" (indicating failure):
solve(2, 0) | +--> solve(1, 0) | +--> solve(0, 0) | +--> return "X" (because we can't move anywhere)So when solve(0, 0) returns "X", we will automatically backtrack to (1, 0), where we try south, but we're blocked, so we try east:
solve(2, 0) | +--> solve(1, 0) | +--> solve(0, 0) | | | +--> return "X" | +--> solve(1, 1)We've found the cup, so return "C", indicating we found the cup.
solve(2, 0) | +--> solve(1, 0) | +--> solve(0, 0) | | | +--> return "X" | +--> solve(1, 1) | +--> return "C"solve(1, 1) returns "C" back to solve(1, 0). What should we do with this "C"? It's not "X", so it indicates a successful search, but what should solve(1, 0) return? We can't just return "C" again, because the cup isn't at (1, 0). Instead, we'll return a string indicating the direction that we walked to find the cup, which was east (so we'll return "E").
solve(2, 0) | +--> solve(1, 0) | +--> solve(0, 0) | | | +--> return "X" | +--> solve(1, 1) | | | +--> return "C" | +--> return "E" (because we walked east to find the cup from here)solve(1, 0) returns "E" back to solve(2, 0), and again, what should solve(2, 0) return? We walked north from (2, 0) to (1, 0), so let's attach an "N" to the front of our answer:
solve(2, 0) | +--> solve(1, 0) | | | +--> solve(0, 0) | | | | | +--> return "X" | | | +--> solve(1, 1) | | | | | +--> return "C" | | | +--> return "E" | +--> return "NE"And therefore the original recursive call so solve(2, 0) returns "NE", indicating the path to the cup from the original starting location is North, then East.
If this makes sense, go back to the previous page and continue.