Day 11 - Flashes of inspiration

This is a problem around having a grid of octopuses that build up energy and flash. That's a fairly simple simulation, the tricky part is that when an octopus flashes it's light, it adds energy to all of its neighbours.

We're going to have to process the octopuses carefully to avoid infinite loops, and to make sure that we've caught all of them.

Luckily, this is problem is almost exactly the same as the problem from a few days ago, and a flood fill algorithm should manage most of it. What we need to be careful of in this case is that an octopus affects its neighbours, so a given octopus can be visited multiple times by the flood fill (which doesn't happen for our previous flood fill), but that it can only flash the once.

The way that I'm going to deal with this is the same flood fill algorithm that we used before, visit all the octopuses (octopi?) that have reached a flash threshold, and for each octopus, we'll add energy to the neighbours. If any have reached flash threshold, we'll add them to teh list. But critically, we won't reset those counters yet, we'll let them keep building up. This means that we should only visit each octopus to make it flash itself if it reached exactly 9, so when we get from 9 to 10, we add the energy but don't add it to the visit list.

So the algorithm will look like:

Start with a tovisit list that is all the octopuses that have 9 energy
Start with an empty  visited list
While theres an octopus in the tovisit list
  Make the octopus flash by adding it to visited list
  Go to each of the neighbours of the octopus adding 1 to their energy level
  If their energy level is now exactly 9, add them to the tovisit list
  Remove the octopus from the tovisit list
Now go through all octopuses that have a value 9 or greater, and set them to 0
return the list of octopuses that flashed

Lets give it a try

Cool, that works on the simple input, lets try it on the test input

That worked, and somewhat to my surprise, I didn't get the numbers wrong in those range arguments. I was expecting at least 1 off by one error!

Onto production input

Ok, onto part 2.

I think the easiest way to do this, via brute force, is to keep looping the execute step until we get a flashes that returns us the length of the input, 100.

Ok, lets try that on prod data