我有以下地图与目标节点“E”:
val map = Map("A" -> "B", "A" -> "C", "C" -> "D", "C" -> "E")
它描述了一个有向节点图,如下所示:
A / \ B C / \ D E
我需要在任何时候输入图表并生成到目标节点的路径。
Example 1: Enter at A -> Route: A->C->E
Example 2: Enter at D -> Route: D->C->E
Example 3: Enter at B -> Route: B->A->C->E
有没有人知道可以做到这一点的紧凑算法,因为之前必须尝试过。
期待您的回复。
干杯,
Jez的
答案 0 :(得分:2)
所以,就是这样:
val map = List("A" -> "B", "A" -> "C", "C" -> "D", "C" -> "E")
def pathOf(tree: Iterable[(String,String)],from: String,to: String, path: List[String] = Nil): List[String] = {
if(from == to) return to::path
tree.filterNot{ case(a,b) => path.contains(a)||path.contains(b) }
.collect{
case (a,b) if a == to => b
case (a,b) if b == to => a
}.map{ x => pathOf(tree,from,x,to::path) }
.find{ _.nonEmpty }
.getOrElse(Nil)
}
用例:
scala> pathOf(map,"B","E").mkString("->")
res1: String = B->A->C->E
scala> pathOf(map,"C","E").mkString("->")
res2: String = C->E
答案 1 :(得分:1)
作为Scala的新手,我认为这个问题对我自己来说是一个很好的练习,并希望与大家分享我的解决方案。欢迎任何评论!
BTW,@ Eastsun给出的解决方案是深度优先搜索,它“记忆”每个路径中的访问节点,而我的是广度优先搜索,不需要记忆(尽管你绝对可以添加此功能来改进效率)。对于树木,他们会得到相同的答案,但对于一般图表,它们可以有所不同。还可以缓存每个节点的邻居以进行优化。
val graph = Vector(("A","B"), ("A","C"), ("C","D"), ("C","E"))
def adjacent(a: String) = {
graph flatMap {
case (`a`, x) => Some(x)
case (x, `a`) => Some(x)
case _ => None
}
}
def go(from: String, to: String) {
def expand(paths: Vector[Vector[String]]) {
paths.find(_.last==to) match {
case Some(x) => println(x); return
case None => expand(paths flatMap { e =>
adjacent(e.last) map (e :+ _)
})
}
}
expand(Vector(Vector(from)))
}
// tests
go("A","E") // Vector(A, C, E)
go("B","E") // Vector(B, A, C, E)
go("D","E") // Vector(D, C, E)
带记忆的版本:更改
adjacent(e.last) map (e :+ _)
到
adjacent(e.last) filterNot (x => paths.flatten contains x) map (e :+ _)
或将此功能放在相邻的功能中。