The core algorithm

It's time to actually implement the core algorithm, which will be surprisingly simple now that we've set up suitable data structures.