Advertisement
jsbrucker

AoC Day12 Part1 - WIP

Dec 12th, 2022
1,067
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.67 KB | None | 0 0
  1. object Day12 {
  2.   def part1(input: Iterator[String]): String = {
  3.     val grid = input.toIndexedSeq
  4.     val startAndEnd = grid.zipWithIndex.flatMap { case (row, i) =>
  5.       row.zipWithIndex.flatMap { case (v, j) =>
  6.         if (v == 'S') Some((v, i, j))
  7.         else if (v == 'E') Some((v, i, j))
  8.         else None
  9.       }
  10.     }
  11.     val heights = grid.map {
  12.       _.map { v =>
  13.         if (v == 'S') 'a'
  14.         else if (v == 'E') 'z'
  15.         else v
  16.       }.map(_ - 'a')
  17.     }
  18.     val start = startAndEnd.find(_._1 == 'S').get
  19.     val end = startAndEnd.find(_._1 == 'E').get
  20.     val path = scala.collection.mutable.IndexedSeq.fill[Option[Int]](heights.size, heights(0).size)(None)
  21.     val toVisit = scala.collection.mutable.Queue((start._2, start._3, 0))
  22.     var found = -1
  23.     var maxH = -1
  24.     var minD = -1
  25.  
  26.     def isValid(i: Int, j: Int): Boolean = i >= 0 && i < grid.size && j >= 0 && j < grid(0).size
  27.  
  28.     while (toVisit.nonEmpty && found == -1) {
  29.       val (y, x, d) = toVisit.removeHead()
  30.       if (y == end._2 && x == end._3) found = d
  31.       if (path(y)(x).isEmpty) {
  32.         path(y)(x) = Some(d)
  33.         val h = heights(y)(x)
  34.         if (maxH < h) {
  35.           maxH = h
  36.           minD = d
  37.         }
  38.         Seq((-1, 0), (1, 0), (0, 1), (0, -1)).foreach { case (i, j) =>
  39.           if (isValid(y + i, x + j)) {
  40.             if ((heights(y + i)(x + j) - h).abs <= 1 && path(y + i)(x + j).isEmpty) {
  41.               toVisit.append((y + i, x + j, d + 1))
  42.             }
  43.           }
  44.         }
  45.       }
  46.     }
  47.     // Added the minD and Math.max here in case it would accept the shortest path to the highest reachable point...
  48.     Math.max(found, minD).toString
  49.   }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement