The Towers of Hanoi asks you to move a stack of differently sized discs from tower A to tower C, one disc at a time, without placing a wider disc on a narrower one. section 1.5
Model each tower as a stack: push adds a disc, and pop removes the top disc. Swift’s Array provides the backing store for this LIFO structure. section 1.5
A recursive solution separates the task into two cases:
- Base case: move one disc directly from the source tower to the destination. section 1.5
- Recursive case: move the upper n−1 discs to the temporary tower, move the remaining disc, then move the n−1 discs onto the destination. section 1.5
- The same procedure can be reused for the smaller subproblems, while the stack operations preserve legal move order. section 1.5
Three discs from A to C
Move the top disc from A to C, the middle disc from A to B, and the top disc from C to B. Move the bottom disc from A to C, then repeat the two-disc procedure from B to C. section 1.5
Figure 1.7. The challenge is to move the three discs, one at a time, from tower A to tower C. A larger disc may never be on top of a smaller disc.
Use the diagram to track the three discs, their source and destination towers, and the rule that larger discs cannot rest on smaller ones. section 1.5
