lib/math/discrete/graph/algorithms.rb
# Dijkstra's algorithm is an algorithm for finding the shortest paths between nodes in a graph.
# The graph must not have negative-weighted edges
# Read more:
# https://en.wikipedia.org/wiki/Dijkstra's_algorithm
Dijkstra's algorithm is an algorithm for finding the shortest paths between nodes in a graph.
Dijkstra ' s algorithm is an algorithm for finding the shortest paths between nodes in a graph .
def dijkstras_algorithm(source, target)
    distance_tree = { source.label => { distance: 0, parent: nil } }
    priority_queue = Containers::PriorityQueue.new do |a,b|
      (distance_tree[a][:distance] <=> distance_tree[b][:distance]) == -1
    end
    vertex_set.each do |vertex|
      unless vertex == source
        distance_tree[vertex.label] = { distance: Float::INFINITY, parent: nil }
      end
      priority_queue.push vertex, vertex.label
    end
    until priority_queue.empty?
      vertex = priority_queue.pop
      vertex.adjacent_vertices.each do |neighbour|
        alt = distance_tree[vertex.label][:distance] + vertex.distance_to(neighbour)
        if alt < distance_tree[neighbour.label][:distance]
          distance_tree[neighbour.label] = { distance: alt, parent: vertex.label }
        end
      end
    end
    distance_tree
  end
def dijkstras_algorithm ( source , target ) distance_tree = { source . label => { distance : 0 , parent : nil } } priority_queue = Containers :: PriorityQueue . new do | a , b | ( distance_tree [ a ] [ :distance ] <=> distance_tree [ b ] [ :distance ] ) == - 1 end vertex_set . each do | vertex | unless vertex == source distance_tree [ vertex . label ] = { distance : Float :: INFINITY , parent : nil } end priority_queue . push vertex , vertex . label end until priority_queue . empty? vertex = priority_queue . pop vertex . adjacent_vertices . each do | neighbour | alt = distance_tree [ vertex . label ] [ :distance ] + vertex . distance_to ( neighbour ) if alt < distance_tree [ neighbour . label ] [ :distance ] distance_tree [ neighbour . label ] = { distance : alt , parent : vertex . label } end end end distance_tree end
Dijkstra's algorithm is an algorithm for finding the shortest paths between nodes in a graph.
Dijkstra ' s algorithm is an algorithm for finding the shortest paths between nodes in a graph .
source
<not_specific>
target
<not_specific>