Backtracking and Branch and Bound: Trying, Undoing and Giving Up Early
You have a combination lock on your bicycle, and you have forgotten the code. It has three digits, so there are a thousand possibilities, 000 to 999. But you do remember one thing: the three digits add up to 10. Do you really have to try all thousand? Of course not. You start with 7, then 5, and you stop right there, because 7 + 5 = 12 is already more than 10, and no third digit can bring it back down. You never turn the third wheel for 7-5. You go back one step, change the 5 to a 2, and carry on. A whole block of 10 codes has been thrown away with one glance.
That small habit, building an answer piece by piece and dropping a half-built answer the moment it cannot work, is the subject of this chapter. In the last chapter every program followed one road to its answer. These programs try a choice, go on, and when the choice leads nowhere, they come back and try the next one. It is called backtracking. Its sibling, branch and bound, does the same for problems where we do not want just any answer but the best one, and it gives up on a branch as soon as the branch cannot beat the best answer found so far.