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.

πŸ‘‹ Do you have a minute?

Please leave your appreciation by commenting on this post!

It takes one minute and is worth it for your career.

Get started

Top comments (0)

Sentry image

See why 4M developers consider Sentry, β€œnot bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

πŸ‘‹ Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay