But although I’d implemented a breadth first search twice already in this year’s Advent of Code challenge, I hadn’t created a generic implementation. A breadth first search needs three things – a starting state, a function that checks if a given state is a “solution”, and a function that returns the next states from a given state. So I decided to make a generic breadth first search that returns a sequence of solution states. It uses a regular .NET Queue<T> for the states to explore, as that has performed well for me previously.

With those generic parts in place, now we need to write the code specific to today’s problem. The state for our problem is the current position and the directions taken to get there. And to check if we’ve solved the problem, we just need to check the current position:

And now to solve part a, we just need to extract the path from the first solution from our searcher. (By the way I finally entered my first wrong answer today. I thought I had to enter the path length rather than the path itself for part a. Very annoying, because my path was correct!)

About Mark Heath

I'm a Microsoft MVP and software developer based in Southampton, England, currently working as a Software Architect for NICE Systems. I create courses for Pluralsight and am the author of several open source libraries. I currently specialize in architecting Azure based systems and audio programming. You can find me on: