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, checking every empty space (.). For each empty space, it places an obstruction (#) temporarily and then checks if placing this obstruction causes the guard to loop by calling the PatrolLoop method.
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.
SOCIAL SHARE CARD GENERATOR