Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var input = await File.ReadAllLinesAsync("input.txt");
- var gridSize = input.Length;
- var grid = new char[gridSize, gridSize];
- var guard = new Position(0, 0);
- var start = new Position(0, 0);
- var visited1 = new HashSet<Position>();
- var guardDirection = Direction.Up;
- for (var row = 0; row < gridSize; row++)
- {
- for (var col = 0; col < gridSize; col++)
- {
- grid[row, col] = input[row][col];
- if (input[row][col] == '^')
- {
- start = new Position(row, col);
- guard = start;
- grid[row, col] = 'X';
- visited1.Add(start);
- }
- }
- }
- var part1 = 1;
- var next = guard.Move(guardDirection);
- while (!next.OutOfBounds(gridSize))
- {
- if (GetValue(next) == '#')
- {
- guardDirection = guardDirection.TurnRight();
- }
- else
- {
- guard = next;
- if (visited1.Add(guard))
- {
- grid[next.Row, next.Col] = 'X';
- part1++;
- }
- }
- next = guard.Move(guardDirection);
- }
- Console.WriteLine($"Part 1: {part1}");
- var part2 = 0;
- var visited2 = new HashSet<(Position, Direction)>(); //We also store the direction for loop detection in Part 2.
- foreach (var position in visited1)
- {
- var currentValue = GetValue(position);
- var row = position.Row;
- var col = position.Col;
- guard = start;
- guardDirection = Direction.Up;
- grid[row, col] = '#';
- visited2.Clear();
- visited2.Add((start, Direction.Up));
- while (!guard.OutOfBounds(gridSize))
- {
- next = guard.Move(guardDirection);
- if (GetValue(next) == '#')
- {
- guardDirection = guardDirection.TurnRight();
- }
- else
- {
- guard = next;
- if (!visited2.Add((guard, guardDirection)))
- {
- part2++;
- break;
- }
- }
- }
- grid[row, col] = currentValue;
- }
- Console.WriteLine($"Part 2: {part2}");
- return;
- char GetValue(Position position)
- {
- return position.OutOfBounds(gridSize) ? default : grid[position.Row, position.Col];
- }
- internal record Direction(int Row, int Col)
- {
- public Direction TurnLeft()
- {
- return new Direction(-Col, Row);
- }
- public Direction TurnRight()
- {
- return new Direction(Col, -Row);
- }
- public static readonly Direction Up = new(-1, 0);
- public static readonly Direction Down = new(1, 0);
- public static readonly Direction Left = new(0, -1);
- public static readonly Direction Right = new(0, 1);
- }
- internal record Position(int Row, int Col)
- {
- public Position Move(Direction dir)
- {
- return new Position(Row + dir.Row, Col + dir.Col);
- }
- public bool OutOfBounds(int size)
- {
- return OutOfBounds(0, size);
- }
- public bool OutOfBounds(int start, int end)
- {
- return Row < start || Row >= end || Col < start || Col >= end;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement