I wrote a function in Scala to find out and return a loopy path in a directed graph. The program is as followed, one of the arguments is a graph presented in an adjacent list, and the other is a start node. It returns a pair including a loopy path by a list of nodes.
I wonder there are more elegant ways to do so. Please share your thoughts if you would like to. Thanks.
def GetACycle(start: String, maps: Map[String, List[String]]): (Boolean, List[String]) = {
def explore(node: String, visits: List[String]): (Boolean, List[String]) = {
if (visits.contains(node)) (true, (visits.+:(node)).reverse)
else {
if (maps(node).isEmpty) (false, List())
else {
val id = maps(node).indexWhere(x => explore(x, visits.+:(node))._1)
if (id.!=(-1))
explore(maps(node)(id), visits.+:(node))
else
(false, List())
}
}
}
explore(start, List())
}
I felt I had to use the indexWhere in this situation, but I suppose it would have other ways to do that.