|
| 1 | +import scala.collection.mutable |
| 2 | + |
| 3 | +object Dijkstras extends App { |
| 4 | + |
| 5 | + val graphs = new SimpleGraph[String]( |
| 6 | + Map( |
| 7 | + "A" -> Map("B" -> 7, "C" -> 8), |
| 8 | + "B" -> Map("A" -> 7, "F" -> 2), |
| 9 | + "C" -> Map("A" -> 8, "G" -> 4, "F" -> 6), |
| 10 | + "D" -> Map("F" -> 8), |
| 11 | + "E" -> Map("H" -> 1), |
| 12 | + "F" -> Map("B" -> 2, "C" -> 6, "D" -> 8, "G" -> 9, "H" -> 1), |
| 13 | + "G" -> Map("C" -> 4, "F" -> 9), |
| 14 | + "H" -> Map("E" -> 1, "F" -> 3) |
| 15 | + ) |
| 16 | + ) |
| 17 | + graphs.getShortestPath("A","E") |
| 18 | +} |
| 19 | + |
| 20 | +case class SimpleGraph[N](succs: Map[N, Map[N, Int]]) { |
| 21 | + |
| 22 | + def apply(n: N) = succs.getOrElse(n, Map.empty) |
| 23 | + |
| 24 | + def initDistance(point:N) = { |
| 25 | + this.succs.foldLeft(Map.empty:Map[N, (Int, Seq[N])]) { |
| 26 | + (result, vertex) => |
| 27 | + if (vertex._1 == point) { |
| 28 | + result ++ Map(point -> (0,Seq(point))) |
| 29 | + } else { |
| 30 | + result ++ Map(vertex._1 -> (Int.MaxValue, Seq(point))) |
| 31 | + } |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + def shortestPath(n:N)(selected:Set[N])(currentDistance:Map[N, (Int, Seq[N])]) = { |
| 36 | + currentDistance.keys.filterNot(selected.contains(_)).foldLeft(n:N) { |
| 37 | + (result, point) => |
| 38 | + currentDistance(point)._1 match { |
| 39 | + case x if result == n => point |
| 40 | + case y if (currentDistance(result)._1 > y) => point |
| 41 | + case _ => result |
| 42 | + } |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + def updateGraph(n:N)(f:N)(distance:Map[N, (Int, Seq[N])]):Map[N, (Int, Seq[N])] = { |
| 47 | + val hereDistance = distance(f) |
| 48 | + this.succs(f).foldLeft(distance:Map[N, (Int, Seq[N])]) { |
| 49 | + (result, vertex) => |
| 50 | + val nodeDistance = hereDistance._1 match { |
| 51 | + case Int.MaxValue => vertex._2 |
| 52 | + case _ => hereDistance._1 + vertex._2 |
| 53 | + } |
| 54 | + if (distance(vertex._1)._1 > nodeDistance) { |
| 55 | + result ++ Map(vertex._1 -> (nodeDistance, hereDistance._2 :+ vertex._1)) |
| 56 | + } else { |
| 57 | + result |
| 58 | + } |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + def getShortestPath(start: N, finish: N) = { |
| 63 | + var nextNode:N = start; |
| 64 | + var currentDistance:Map[N, (Int, Seq[N])] = initDistance(start); |
| 65 | + var unreachedVertexSet:Set[N] = succs.keySet.filterNot(_ == start) |
| 66 | + while (!unreachedVertexSet.isEmpty) { |
| 67 | + currentDistance = updateGraph(start)(nextNode)(currentDistance) |
| 68 | + nextNode = shortestPath(start)(succs.keySet.filterNot(unreachedVertexSet.contains(_)))(currentDistance) // 次のノードを決定させる |
| 69 | + unreachedVertexSet = unreachedVertexSet.-(nextNode) |
| 70 | + } |
| 71 | + println("result : ", currentDistance(finish)._2.reverse.toSeq) |
| 72 | + } |
| 73 | + |
| 74 | +} |
0 commit comments