This one was tricky to visualize in any interesting way, so here's a total spoiler for the algorithm I used. Fun fact: moving from part 1 to part 2 was a single-character change.