--- Day 20: Race Condition ---

The Historians are quite pixelated again. This time, a massive, black building looms over you - you're right outside the CPU!

While The Historians get to work, a nearby program sees that you're idle and challenges you to a race. Apparently, you've arrived just in time for the frequently-held race condition festival!

The race takes place on a particularly long and twisting code path; programs compete to see who can finish in the fewest picoseconds. The winner even gets their very own mutex!

They hand you a map of the racetrack (your puzzle input). For example:

###############
#...#...#.....#
#.#.#.#.#.###.#
#S#...#.#.#...#
#######.#.#.###
#######.#.#...#
#######.#.###.#
###..E#...#...#
###.#######.###
#...###...#...#
#.#####.#.###.#
#.#...#.#.#...#
#.#.#.#.#.#.###
#...#...#...###
###############
The map consists of track (.) - including the start (S) and end (E) positions (both of which also count as track) - and walls (#).

When a program runs through the racetrack, it starts at the start position. Then, it is allowed to move up, down, left, or right; each such move takes 1 picosecond. The goal is to reach the end position as quickly as possible. In this example racetrack, the fastest time is 84 picoseconds.

Because there is only a single path from the start to the end and the programs all go the same speed, the races used to be pretty boring. To make things more interesting, they introduced a new rule to the races: programs are allowed to cheat.

The rules for cheating are very strict. Exactly once during a race, a program may disable collision for up to 2 picoseconds. This allows the program to pass through walls as if they were regular track. At the end of the cheat, the program must be back on normal track again; otherwise, it will receive a segmentation fault and get disqualified.

So, a program could complete the course in 72 picoseconds (saving 12 picoseconds) by cheating for the two moves marked 1 and 2:

###############
#...#...12....#
#.#.#.#.#.###.#
#S#...#.#.#...#
#######.#.#.###
#######.#.#...#
#######.#.###.#
###..E#...#...#
###.#######.###
#...###...#...#
#.#####.#.###.#
#.#...#.#.#...#
#.#.#.#.#.#.###
#...#...#...###
###############
Or, a program could complete the course in 64 picoseconds (saving 20 picoseconds) by cheating for the two moves marked 1 and 2:

###############
#...#...#.....#
#.#.#.#.#.###.#
#S#...#.#.#...#
#######.#.#.###
#######.#.#...#
#######.#.###.#
###..E#...12..#
###.#######.###
#...###...#...#
#.#####.#.###.#
#.#...#.#.#...#
#.#.#.#.#.#.###
#...#...#...###
###############
This cheat saves 38 picoseconds:

###############
#...#...#.....#
#.#.#.#.#.###.#
#S#...#.#.#...#
#######.#.#.###
#######.#.#...#
#######.#.###.#
###..E#...#...#
###.####1##.###
#...###.2.#...#
#.#####.#.###.#
#.#...#.#.#...#
#.#.#.#.#.#.###
#...#...#...###
###############
This cheat saves 64 picoseconds and takes the program directly to the end:

###############
#...#...#.....#
#.#.#.#.#.###.#
#S#...#.#.#...#
#######.#.#.###
#######.#.#...#
#######.#.###.#
###..21...#...#
###.#######.###
#...###...#...#
#.#####.#.###.#
#.#...#.#.#...#
#.#.#.#.#.#.###
#...#...#...###
###############
Each cheat has a distinct start position (the position where the cheat is activated, just before the first move that is allowed to go through walls) and end position; cheats are uniquely identified by their start position and end position.

In this example, the total number of cheats (grouped by the amount of time they save) are as follows:

There are 14 cheats that save 2 picoseconds.
There are 14 cheats that save 4 picoseconds.
There are 2 cheats that save 6 picoseconds.
There are 4 cheats that save 8 picoseconds.
There are 2 cheats that save 10 picoseconds.
There are 3 cheats that save 12 picoseconds.
There is one cheat that saves 20 picoseconds.
There is one cheat that saves 36 picoseconds.
There is one cheat that saves 38 picoseconds.
There is one cheat that saves 40 picoseconds.
There is one cheat that saves 64 picoseconds.
You aren't sure what the conditions of the racetrack will be like, so to give yourself as many options as possible, you'll need a list of the best cheats. How many cheats would save you at least 100 picoseconds?
// solution for https://adventofcode.com/2024/day/20 part 1

"use strict"

const input = Deno.readTextFileSync("day20-input.txt").trim()

const map = [ ]

var width = 0
var height = 0

var homeCell = null

var goalCell = null

var bestShortcuts = 0


function main() {

    processInput()
    
    walk()
    
    findAllShortcuts()
    
    console.log("the answer is", bestShortcuts)
}

function processInput() {
    
    const rawLines = input.split("\n")
    
    let row = -1
    for (const rawLine of rawLines) { 
    
        row += 1
        const mapLine = [ ]
        map.push(mapLine)
        
        let col = -1
        for (const symbol of rawLine.trim()) {
        
            col += 1

            const cell = createCell(row, col, symbol)
            
            if (symbol == "S") { homeCell = cell }
            if (symbol == "E") { goalCell = cell }

            mapLine.push(cell)       
        }
    }
    
    height = map.length
    width = map[0].length
}

function createCell(row, col, symbol) {

    return { "row": row, "col": col, "symbol": symbol, "distance": -1 }
}

///////////////////////////////////////////////////////////////////////////////

function walk() {

    homeCell.distance = 0

    let cellsToWalk = [ homeCell ]

    while (true) {
        
        const newCellsToWalk = [ ]
    
        for (const cell of cellsToWalk) {
        
            const row = cell.row
            const col = cell.col
            const distance = cell.distance + 1
            
            if (cell == goalCell) { return } // not necessary for my input
            
            grabCell(row - 1, col, distance, newCellsToWalk)
            grabCell(row + 1, col, distance, newCellsToWalk)
            grabCell(row, col - 1, distance, newCellsToWalk)
            grabCell(row, col + 1, distance, newCellsToWalk)
        }
        
        cellsToWalk = newCellsToWalk
        
        if (cellsToWalk.length == 0) { return }        
    }
}

function grabCell(row, col, distance, newCellsToWalk) {

    if (row < 0) { return }
    if (col < 0) { return }
    
    if (row == height) { return }
    if (col == width)  { return }

    const cell = map[row][col]
    
    if (cell.symbol == "#") { return }
    
    if (cell.distance != -1) { return }
    
    cell.distance = distance  
    
    newCellsToWalk.push(cell)
}

///////////////////////////////////////////////////////////////////////////////

function findAllShortcuts() {

    for (const line of map) {
    
        for (const cell of line) { 
        
            if (cell.symbol != "#") { continue }
            
            if (cell.row == 0) { continue }
            if (cell.col == 0) { continue }
            
            if (cell.row == height - 1) { continue }
            if (cell.col == width  - 1) { continue }
        
            findShortcut(cell) 
        }    
    }
}

function findShortcut(cell) {
    
    const north = map[cell.row - 1][cell.col]
    const south = map[cell.row + 1][cell.col]
    const east  = map[cell.row][cell.col + 1]
    const west  = map[cell.row][cell.col - 1]
    
    const neighbors = [ ] // only cells that are in the path

    if (north.distance != -1) { neighbors.push(north) }
    if (south.distance != -1) { neighbors.push(south) }
    if (east.distance  != -1) { neighbors.push(east)  }
    if (west.distance  != -1) { neighbors.push(west)  }
    
    if (neighbors.length < 2) { return }
    
    orderByDistance(neighbors)

    const cellBeforeCut = neighbors.shift()
    
    const distanceBeforeCut = cellBeforeCut.distance
    
    for (const neighbor of neighbors) {
    
        const distanceAfterCut = neighbor.distance
        
        const economy = distanceAfterCut - distanceBeforeCut - 2
    
        if (economy >= 100) { bestShortcuts += 1 }    
    } 
}

///////////////////////////////////////////////////////////////////////////////

function orderByDistance(list) {

    let n = -1
    
    while (true) {
    
        n += 1
    
        const a = list[n]
        const b = list[n + 1]
        
        if (b == undefined) { return }
    
        if (a.distance < b.distance) { continue }
        
        list[n] = b
        list[n + 1] = a
    
        n = -1
    }
}

console.time("execution time")
main()
console.timeEnd("execution time") // 16ms