Skip to content

Instantly share code, notes, and snippets.

@ivan-klass
Created February 28, 2022 11:15
Show Gist options
  • Save ivan-klass/2d2f8a9b6cfa349cc93f534dd9612d79 to your computer and use it in GitHub Desktop.
Save ivan-klass/2d2f8a9b6cfa349cc93f534dd9612d79 to your computer and use it in GitHub Desktop.
Shortest labyrinth path
type Point = (Int, Int)
case class StateVars(pathLength: Int, seen: Set[Point], starts: Set[Point])
// lab is 2-dimension array either of enterable cell (true) or obsticle (false)
def solve(start: Point, end: Point, lab: Vector[Vector[Boolean]]): Int = {
State[StateVars, Boolean] { case StateVars(pathLength, seen, expandFrom) =>
val nextArea = expandFrom.flatMap { case (x, y) =>
Set((x - 1, y), (x + 1, y), (x, y + 1), (x, y - 1)).filterNot(seen).filter {
case (nx, ny) => nx >= 0 && nx < lab.size && ny >=0 && ny < lab(0).size && lab(nx)(ny)
}
}
(StateVars(pathLength + 1, seen ++ expandFrom, nextArea), nextArea(end))
}.iterateWhile(!_).runS(StateVars(0, Set.empty, Set(start))).value.pathLength
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment