Это у вас работает?
package foo
object Foo {
def main(args: Array[String]): Unit = {
val edges = List(
List((1, 1), (2, 3), (4, 10)),
List((2, 1)),
List((3, 1), (4, 5)),
List((4, 1)),
List())
println(hasMaxCostPath(edges,0,1,2))
println(hasMaxCostPath(edges,0,2,2))
}
def hasMaxCostPath(edges: List[List[(Int, Int)]], start: Int, end: Int, maxCost: Int): Boolean = {
maxCost > 0 &&
edges(start).exists(a =>
(a._1 == end && a._2 <= maxCost) ||
hasMaxCostPath(edges, a._1, end, maxCost - a._2)
)
}
}
Редактировать: ====
Приведенное выше решение не учитывает параметр длины.
Вот решение с параметром длины:
package foo
object Foo {
def main(args: Array[String]): Unit = {
val edges = List(
List((1, 1), (2, 3), (4, 10)),
List((2, 1)),
List((3, 1), (4, 5)),
List((4, 1)),
List())
assert(! hasMaxCostPath(edges,0,4,4,3))
assert(hasMaxCostPath(edges,0,4,4,4))
}
def hasMaxCostPath(edges: List[List[(Int, Int)]], start: Int, end: Int, maxCost: Int, maxLength: Int): Boolean = {
maxLength > 0 &&
maxCost >= 0 &&
edges(start).exists(a =>
(a._1 == end && a._2 <= maxCost) ||
hasMaxCostPath(edges, a._1, end, maxCost - a._2, maxLength - 1)
)
}
}
=== Редактировать:
И вот решение, включающее вашу вторую проблему:
package foo
object Foo {
def main(args: Array[String]): Unit = {
val edges = List(
List((1, 1), (2, 3), (4, 10)),
List((2, 1)),
List((3, 1), (4, 5)),
List((4, 1)),
List())
assert(! hasMaxCostPath(edges,0,4,4,3))
assert(hasMaxCostPath(edges,0,4,4,4))
assert(getMaxCostPaths(edges,0,0,5,5) == List())
assert(getMaxCostPaths(edges,0,1,1,1) == List(List(0,1)))
assert(getMaxCostPaths(edges,0,2,2,2) == List(List(0,1,2)))
assert(getMaxCostPaths(edges,0,2,5,5) == List(List(0,2), List(0,1,2)))
}
def hasMaxCostPath(edges: List[List[(Int, Int)]], start: Int, end: Int, maxCost: Int, maxLength: Int): Boolean = {
maxLength > 0 &&
maxCost >= 0 &&
edges(start).exists(a =>
(a._1 == end && a._2 <= maxCost) ||
hasMaxCostPath(edges, a._1, end, maxCost - a._2, maxLength - 1)
)
}
def getMaxCostPaths(
edges: List[List[(Int, Int)]],
from: Int, to: Int,
maxCost: Int,
maxLength: Int): List[List[Int]] = {
getMaxCostPathsRec(edges, from, to, maxCost, maxLength, List(from))
}
def getMaxCostPathsRec(
edges: List[List[(Int, Int)]],
start: Int, end: Int,
maxCost: Int,
maxLength: Int,
path: List[Int]) : List[List[Int]] = {
if (maxLength <= 0 || maxCost < 0) return List()
val direct = edges(start).filter(a => a._1 == end && a._2 <= maxCost).map(edge => path ::: List(edge._1))
val transitive = edges(start).flatMap(a =>
getMaxCostPathsRec(edges, a._1, end, maxCost - a._2, maxLength - 1, path ::: List(a._1))
)
direct ::: transitive
}
}