--- Day 16: Reindeer Maze ---

It's time again for the Reindeer Olympics! This year, the big event is the Reindeer Maze, where the Reindeer compete for the lowest score.

You and The Historians arrive to search for the Chief right as the event is about to start. It wouldn't hurt to watch a little, right?

The Reindeer start on the Start Tile (marked S) facing East and need to reach the End Tile (marked E). They can move forward one tile at a time (increasing their score by 1 point), but never into a wall (#). They can also rotate clockwise or counterclockwise 90 degrees at a time (increasing their score by 1000 points).

To figure out the best place to sit, you start by grabbing a map (your puzzle input) from a nearby kiosk. For example:

###############
#.......#....E#
#.#.###.#.###.#
#.....#.#...#.#
#.###.#####.#.#
#.#.#.......#.#
#.#.#####.###.#
#...........#.#
###.#.#####.#.#
#...#.....#.#.#
#.#.#.###.#.#.#
#.....#...#.#.#
#.###.#.#.#.#.#
#S..#.....#...#
###############
There are many paths through this maze, but taking any of the best paths would incur a score of only 7036. This can be achieved by taking a total of 36 steps forward and turning 90 degrees a total of 7 times:


###############
#.......#....E#
#.#.###.#.###^#
#.....#.#...#^#
#.###.#####.#^#
#.#.#.......#^#
#.#.#####.###^#
#..>>>>>>>>v#^#
###^#.#####v#^#
#>>^#.....#v#^#
#^#.#.###.#v#^#
#^....#...#v#^#
#^###.#.#.#v#^#
#S..#.....#>>^#
###############
Here's a second example:

#################
#...#...#...#..E#
#.#.#.#.#.#.#.#.#
#.#.#.#...#...#.#
#.#.#.#.###.#.#.#
#...#.#.#.....#.#
#.#.#.#.#.#####.#
#.#...#.#.#.....#
#.#.#####.#.###.#
#.#.#.......#...#
#.#.###.#####.###
#.#.#...#.....#.#
#.#.#.#####.###.#
#.#.#.........#.#
#.#.#.#########.#
#S#.............#
#################
In this maze, the best paths cost 11048 points; following one such path would look like this:

#################
#...#...#...#..E#
#.#.#.#.#.#.#.#^#
#.#.#.#...#...#^#
#.#.#.#.###.#.#^#
#>>v#.#.#.....#^#
#^#v#.#.#.#####^#
#^#v..#.#.#>>>>^#
#^#v#####.#^###.#
#^#v#..>>>>^#...#
#^#v###^#####.###
#^#v#>>^#.....#.#
#^#v#^#####.###.#
#^#v#^........#.#
#^#v#^#########.#
#S#>>^..........#
#################
Note that the path shown above includes one 90 degree turn as the very first move, rotating the Reindeer from facing East to facing North.

Analyze your map carefully. What is the lowest score a Reindeer could possibly get?

Your puzzle answer was 94444.

--- Part Two ---

Now that you know what the best paths look like, you can figure out the best spot to sit.

Every non-wall tile (S, ., or E) is equipped with places to sit along the edges of the tile. While determining which of these tiles would be the best spot to sit depends on a whole bunch of factors (how comfortable the seats are, how far away the bathrooms are, whether there's a pillar blocking your view, etc.), the most important factor is whether the tile is on one of the best paths through the maze. If you sit somewhere else, you'd miss all the action!

So, you'll need to determine which tiles are part of any best path through the maze, including the S and E tiles.

In the first example, there are 45 tiles (marked O) that are part of at least one of the various best paths through the maze:

###############
#.......#....O#
#.#.###.#.###O#
#.....#.#...#O#
#.###.#####.#O#
#.#.#.......#O#
#.#.#####.###O#
#..OOOOOOOOO#O#
###O#O#####O#O#
#OOO#O....#O#O#
#O#O#O###.#O#O#
#OOOOO#...#O#O#
#O###.#.#.#O#O#
#O..#.....#OOO#
###############
In the second example, there are 64 tiles that are part of at least one of the best paths:

#################
#...#...#...#..O#
#.#.#.#.#.#.#.#O#
#.#.#.#...#...#O#
#.#.#.#.###.#.#O#
#OOO#.#.#.....#O#
#O#O#.#.#.#####O#
#O#O..#.#.#OOOOO#
#O#O#####.#O###O#
#O#O#..OOOOO#OOO#
#O#O###O#####O###
#O#O#OOO#..OOO#.#
#O#O#O#####O###.#
#O#O#OOOOOOO..#.#
#O#O#O#########.#
#O#OOO..........#
#################
Analyze your map further. How many tiles are part of at least one of the best paths through the maze?
class MinHeap
  def initialize
    @heap = []
  end

  def push(item)
    @heap.push(item)
    sift_up(@heap.length - 1)
  end

  def pop
    return nil if @heap.empty?

    top = @heap[0]
    last = @heap.pop
    if @heap.any?
      @heap[0] = last
      sift_down(0)
    end
    top
  end

  def empty?
    @heap.empty?
  end

  private

  def sift_up(index)
    while index > 0
      parent = (index - 1) / 2
      break if @heap[parent][0] <= @heap[index][0]
      @heap[parent], @heap[index] = @heap[index], @heap[parent]
      index = parent
    end
  end

  def sift_down(index)
    size = @heap.length
    while true
      left = 2 * index + 1
      right = 2 * index + 2
      smallest = index

      if left < size && @heap[left][0] < @heap[smallest][0]
        smallest = left
      end

      if right < size && @heap[right][0] < @heap[smallest][0]
        smallest = right
      end

      break if smallest == index
      @heap[index], @heap[smallest] = @heap[smallest], @heap[index]
      index = smallest
    end
  end
end

def part2(puzzle_input)
  grid = puzzle_input.split("\n")
  m, n = grid.length, grid[0].length
  start = nil
  end_pos = nil

  # Find start and end positions
  grid.each_with_index do |row, i|
    row.each_char.with_index do |char, j|
      if char == 'S'
        start = [i, j]
      elsif char == 'E'
        end_pos = [i, j]
      end
    end
  end

  grid[end_pos[0]] = grid[end_pos[0]].sub('E', '.')

  # Initialize variables
  visited = {}
  directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]
  heap = MinHeap.new
  heap.push([0, 0, *start, Set.new([start])]) # start with (score, direction, i, j, path)
  lowest_score = nil
  winning_paths = Set.new

  # Function to check if we can visit a position
  def can_visit(visited, d, i, j, score)
    prev_score = visited[[d, i, j]]
    return false if prev_score && prev_score < score
    visited[[d, i, j]] = score
    true
  end

  # Dijkstra-like algorithm
  while !heap.empty?
    score, d, i, j, path = heap.pop

    if lowest_score && lowest_score < score
      break
    end

    if [i, j] == end_pos
      lowest_score = score
      winning_paths.merge(path)
      next
    end

    if !can_visit(visited, d, i, j, score)
      next
    end

    # Move in the current direction
    x, y = i + directions[d][0], j + directions[d][1]
    if grid[x][y] == '.' && can_visit(visited, d, x, y, score + 1)
      heap.push([score + 1, d, x, y, path + [[x, y]]])
    end

    # Turn left
    left = (d - 1) % 4
    if can_visit(visited, left, i, j, score + 1000)
      heap.push([score + 1000, left, i, j, path])
    end

    # Turn right
    right = (d + 1) % 4
    if can_visit(visited, right, i, j, score + 1000)
      heap.push([score + 1000, right, i, j, path])
    end
  end

  winning_paths.length
end

# Read input file and execute the function
input_text = File.read('input.txt')
res = part2(input_text)
puts res