Created
February 28, 2022 11:15
-
-
Save ivan-klass/2d2f8a9b6cfa349cc93f534dd9612d79 to your computer and use it in GitHub Desktop.
Shortest labyrinth path
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
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