All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.autonomousapps.graph.ShortestPath.kt Maven / Gradle / Ivy

There is a newer version: 2.0.2
Show newest version
package com.autonomousapps.graph

import java.util.*

internal class ShortestPath(
  graph: DependencyGraph,
  source: Node
) {

  private val distTo = linkedMapOf()
  private val edgeTo = linkedMapOf()

  init {
    if (!graph.hasNode(source)) {
      missingNode(source)
    }

    for (node in graph.nodes()) {
      distTo[node.identifier] = Float.POSITIVE_INFINITY
    }
    distTo[source.identifier] = 0f

    // visit vertices in topological order
    val top = Topological(graph)
    for (node in top.order()) {
      for (edge in graph.adj(node)) {
        relax(edge)
      }
    }
  }

  fun distTo(other: Node): Float = distTo[other.identifier] ?: missingNode(other)

  fun hasPathTo(other: Node): Boolean = hasPathTo(other.identifier)

  fun hasPathTo(other: String): Boolean {
    return distTo[other]!! < Int.MAX_VALUE
  }

  fun pathTo(other: Node): Iterable? = pathTo(other.identifier)

  fun pathTo(other: String): Iterable? {
    if (!hasPathTo(other)) return null

    val path = Stack()
    var e = edgeTo[other]
    while (e != null) {
      path.push(e)
      e = edgeTo[e.from.identifier]
    }
    return path
  }

  private fun relax(edge: Edge) {
    val v = edge.from
    val w = edge.to

    if (distTo[w.identifier]!! > distTo[v.identifier]!! + edge.weight) {
      distTo[w.identifier] = distTo[v.identifier]!! + edge.weight
      edgeTo[w.identifier] = edge
    }
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy