Created
December 13, 2022 01:23
-
-
Save z3bi/fbd566319256718d89d08ac9b4f9f005 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
var input = """ | |
Sabqponm | |
abcryxxl | |
accszExk | |
acctuvwj | |
abdefghi | |
""" | |
let part = 1 | |
let lines = input.split(whereSeparator: \.isNewline) | |
struct Position: Equatable, Hashable { | |
let x: Int | |
let y: Int | |
let z: UInt8 | |
func canGo(newPosition: Position) -> Bool { | |
return newPosition.z <= z + 1 | |
} | |
} | |
var goal: Position? | |
let gridWidth = lines[0].count | |
let gridHeight = lines.count | |
var starters: [Position] = [] | |
var map: [[UInt8]] = [] | |
for (rowNum, line) in lines.enumerated() { | |
var col: [UInt8] = [] | |
for (colNum, char) in line.enumerated() { | |
var value = char.asciiValue! | |
if char == "S" { | |
value = Character("a").asciiValue! | |
starters.append(Position(x: colNum, y: rowNum, z: value)) | |
} else if char == "E" { | |
value = Character("z").asciiValue! | |
goal = Position(x: colNum, y: rowNum, z: value) | |
} else if char == "a" && part == 2 { | |
starters.append(Position(x: colNum, y: rowNum, z: value)) | |
} | |
col.append(value) | |
} | |
map.append(col) | |
} | |
var paths: [Position] = starters | |
var traversed: Set<Position> = Set(starters) | |
var stepCount = 1 | |
var didFindGoal = false | |
while(!didFindGoal) { | |
var nextLevel: [Position] = [] | |
for path in paths { | |
let coords = [ | |
(x: path.x, y: path.y + 1), | |
(x: path.x, y: path.y - 1), | |
(x: path.x + 1, y: path.y), | |
(x: path.x - 1, y: path.y), | |
] | |
let newSteps: [Position] = coords.compactMap { coord in | |
if coord.x < 0 || coord.y < 0 || coord.x >= gridWidth || coord.y >= gridHeight { | |
return nil | |
} | |
let position = Position(x: coord.x, y: coord.y, z: map[coord.y][coord.x]) | |
if !path.canGo(newPosition: position) { | |
return nil | |
} | |
return position | |
} | |
for step in newSteps { | |
if !traversed.contains(step) { | |
nextLevel.append(step) | |
traversed.insert(step) | |
} | |
} | |
} | |
paths = nextLevel | |
for step in nextLevel { | |
if step == goal { | |
didFindGoal = true | |
print(">> Steps \(stepCount)") | |
} | |
} | |
stepCount += 1 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment