|
| 1 | +import scala.annotation.tailrec |
| 2 | + |
| 3 | +trait Path { |
| 4 | + def edges: Seq[Edge] |
| 5 | +} |
| 6 | + |
| 7 | +case class ExistingPath(edges: Seq[Edge]) extends Path |
| 8 | + |
| 9 | +object EmptyPath extends Path { |
| 10 | + override def edges: Seq[Edge] = Seq.empty |
| 11 | +} |
| 12 | + |
| 13 | +case class Vertex(id: String) |
| 14 | + |
| 15 | +case class Edge(from: Vertex, to: Vertex, distance: Int) |
| 16 | + |
| 17 | +case class Graph(edges: List[Edge]) { |
| 18 | + |
| 19 | + implicit object EdgesOrdering extends Ordering[Edge] { |
| 20 | + def compare(a: Edge, b: Edge) = a.distance compare b.distance |
| 21 | + } |
| 22 | + |
| 23 | + @tailrec |
| 24 | + final def dijkstra(start: Vertex, pathComposition: Path = EmptyPath): Path = { |
| 25 | + val startEdges: Seq[Edge] = edges.filter(_.from == start).sorted |
| 26 | + val smallestDistance: Option[Edge] = startEdges |
| 27 | + .filter(e => !pathComposition.edges.map(_.from).contains(e.to)) |
| 28 | + .headOption |
| 29 | + |
| 30 | + smallestDistance match { |
| 31 | + case Some(distance) => |
| 32 | + dijkstra( |
| 33 | + distance.to, |
| 34 | + ExistingPath(edges = pathComposition.edges.appended(distance)) |
| 35 | + ) |
| 36 | + case None => pathComposition |
| 37 | + } |
| 38 | + } |
| 39 | +} |
| 40 | + |
| 41 | +object Main extends App { |
| 42 | + |
| 43 | + val startA: Vertex = Vertex("A") |
| 44 | + val graph: Graph = Graph( |
| 45 | + edges = List( |
| 46 | + Edge(from = Vertex("A"), to = Vertex("B"), distance = 1), |
| 47 | + Edge(from = Vertex("A"), to = Vertex("C"), distance = 4), |
| 48 | + Edge(from = Vertex("B"), to = Vertex("A"), distance = 1), |
| 49 | + Edge(from = Vertex("B"), to = Vertex("C"), distance = 2), |
| 50 | + Edge(from = Vertex("B"), to = Vertex("D"), distance = 5), |
| 51 | + Edge(from = Vertex("C"), to = Vertex("A"), distance = 4), |
| 52 | + Edge(from = Vertex("C"), to = Vertex("B"), distance = 2), |
| 53 | + Edge(from = Vertex("C"), to = Vertex("D"), distance = 1), |
| 54 | + Edge(from = Vertex("D"), to = Vertex("B"), distance = 5), |
| 55 | + Edge(from = Vertex("D"), to = Vertex("C"), distance = 1) |
| 56 | + ) |
| 57 | + ) |
| 58 | + |
| 59 | + val result: Path = graph.dijkstra(start = startA) |
| 60 | + println("Calculating path...") |
| 61 | + println(s"Result: ${result.edges}") |
| 62 | +} |
0 commit comments