DEV Community

Cover image for AoC '24 - Day 6: Guard Gallivant
Grant Riordan
Grant Riordan

Posted on

AoC '24 - Day 6: Guard Gallivant

Part 1

Part 1, I traverse the grid until hitting an obstacle, where I update the currentRow and column implementing the rule of "always turn right".

Using a HashSet we're able to store the unique visited nodes, and then simply count them.

Part 2:

As in Part 1, we simulate the path of the Guard, however this time round we're also checking for loops.

To detect if the guard enters a loop, a visited set HashSet<(int, int, int, int)> keeps track of the guard's position and its current movement direction. If the guard visits the same spot with the same direction again, it's considered a loop (we know they can pass the same spot in multiple directions with different origin), and the simulation stops

Placing an Obstruction:
The solution loops through every possible location in the grid (based on where we've already been (i.e we only use the stops we know the guard would have visited without any new obstacles).

For each empty space, it places an obstruction (#) temporarily and then checks if placing this obstruction causes the guard to loop.

This improves performance, as we're not checking stops, which never would have been hit without new obstacles.

Repo

Apologies, for the brief explanation, but the code speaks for itself on this case, a lot of loops, checking for obstacles and moving (no real fancy logic i'm afraid).

As always feel free to follow for more solutions and coding tips, or drop me a follow on twitter, where I post about all my blogs, articles and more.

Top comments (0)