DEV Community

Cover image for Advent of Code 2024: Day 6: Guard Gallivant
Grant Riordan
Grant Riordan

Posted on β€’ Edited on

6

Advent of Code 2024: 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.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

πŸ‘‹ Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay