Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- object Day12 {
- def part1(input: Iterator[String]): String = {
- val grid = input.toIndexedSeq
- val startAndEnd = grid.zipWithIndex.flatMap { case (row, i) =>
- row.zipWithIndex.flatMap { case (v, j) =>
- if (v == 'S') Some((v, i, j))
- else if (v == 'E') Some((v, i, j))
- else None
- }
- }
- val heights = grid.map {
- _.map { v =>
- if (v == 'S') 'a'
- else if (v == 'E') 'z'
- else v
- }.map(_ - 'a')
- }
- val start = startAndEnd.find(_._1 == 'S').get
- val end = startAndEnd.find(_._1 == 'E').get
- val path = scala.collection.mutable.IndexedSeq.fill[Option[Int]](heights.size, heights(0).size)(None)
- val toVisit = scala.collection.mutable.Queue((start._2, start._3, 0))
- var found = -1
- var maxH = -1
- var minD = -1
- def isValid(i: Int, j: Int): Boolean = i >= 0 && i < grid.size && j >= 0 && j < grid(0).size
- while (toVisit.nonEmpty && found == -1) {
- val (y, x, d) = toVisit.removeHead()
- if (y == end._2 && x == end._3) found = d
- if (path(y)(x).isEmpty) {
- path(y)(x) = Some(d)
- val h = heights(y)(x)
- if (maxH < h) {
- maxH = h
- minD = d
- }
- Seq((-1, 0), (1, 0), (0, 1), (0, -1)).foreach { case (i, j) =>
- if (isValid(y + i, x + j)) {
- if ((heights(y + i)(x + j) - h).abs <= 1 && path(y + i)(x + j).isEmpty) {
- toVisit.append((y + i, x + j, d + 1))
- }
- }
- }
- }
- }
- // Added the minD and Math.max here in case it would accept the shortest path to the highest reachable point...
- Math.max(found, minD).toString
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement