Post #4275918
2026-07-31 10:50 UTC
Replies (2)
-
@barubary@infosec.exchange 2026-07-31 10:55
@simontatham@hachyderm.io I've had similar thoughts. I think recursive algorithms come most naturally when you have a recursive problem/data structure, like a tree. So I think good introductory examples would be recursively searching a directory for all .png files or eval'ing an expression tree in a calculator.
-
@simontatham@hachyderm.io 2026-07-31 10:50
The best example I've ever managed to come up with is the search problem in the game of Boggle: find a path through a grid of letters, never revisiting a square, that spells out a word. You can simplify the problem by giving a _specific_ word as input rather than a whole dictionary: "is there any path in this grid that spells BANANA?" It's a bit awkward because "never revisit a square" means you have to maintain a set of disallowed squares, either passing a modified copy to each recursive call or modifying a single copy in place. But unfortunately that property is also what makes the problem need recursion in the first place: if you take away that rule, it becomes a much simpler BFS problem – in particular, polynomial time, whereas the proper Boggle search problem is NP-complete. Boggle is in my second category: it's not _impossible_ to solve it non-recursively, but the most obvious alternative technique is breadth-first search, and the "never revisit a square" rule means each entry in the BFS queue has to contain a set of squares, so that lots of queue entries can share the same (grid square, position in word) values and still need to be kept separate. So you can see that there's a memory-use disadvantage: the recursive solution considers all the same cases, but keeps far fewer of them in memory at a time.