import Foundation struct Coord : Hashable, CustomStringConvertible { let (x, y): (Int, Int) var description: String { return "(\(x),\(y))" } } func readInput(_ fileName: String) throws -> [Coord] { let xy = try Regex(#"([0-9]+),([0-9]+)"#) return try String(contentsOfFile: fileName, encoding: .ascii) .split(separator: "\n") .compactMap { $0.wholeMatch(of: xy) } .map { Coord( x: Int($0.output[1].substring!)!, y: Int($0.output[2].substring!)! ) } } struct Map : CustomStringConvertible { let walls: Set let (w, h): (Int, Int) var description: String { let top = " \u{001B}[4m" + (0.. Int? { var q = Heap<(Coord, Int)>(comparator: { l, r in l.1 < r.1 }) var seen: Set = [start] q.insert((start, 0)) while let (cell, cost) = q.pop() { if cell == end { return cost } [(0, -1), (0, 1), (-1, 0), (1, 0)].map { dy, dx in Coord(x: cell.x + dx, y: cell.y + dy)} .filter { c in c.x >= 0 && c.y >= 0 && c.x < w && c.y < h } .filter { !seen.contains($0) } .filter { !walls.contains($0) } .forEach { neighbor in seen.insert(neighbor) q.insert((neighbor, cost + 1)) } } return nil } } @main struct AoC { static func main() throws { let bytes = try readInput(CommandLine.arguments[1]) let w = Int(CommandLine.arguments[2]) ?? 71 let h = Int(CommandLine.arguments[3]) ?? 71 let limit = Int(CommandLine.arguments[4]) ?? 1024 let map = Map(walls: Set(bytes.prefix(limit)), w: w, h: h) print(map) print(map.dijkstra( from: Coord(x: 0, y: 0), to: Coord(x: map.w - 1, y: map.h - 1) ) ?? "no solution") } }