Skip to content

Instantly share code, notes, and snippets.

@flyptkarsh
Last active March 3, 2024 20:42
Show Gist options
  • Select an option

  • Save flyptkarsh/8207245db7c9a77acb7564f47c720f32 to your computer and use it in GitHub Desktop.

Select an option

Save flyptkarsh/8207245db7c9a77acb7564f47c720f32 to your computer and use it in GitHub Desktop.
Dijkstra’s Shortest Path Algorithm (without comments)
graph = {
'A' => { 'B' => 1, 'C' => 4 },
'B' => { 'A' => 1, 'C' => 2, 'D' => 5 },
'C' => { 'A' => 4, 'B' => 2, 'D' => 1 },
'D' => { 'B' => 5, 'C' => 1 }
}
def dijkstra(graph, start)
distances = {}
visited = {}
nodes = graph.keys
nodes.each { |node| distances[node] = Float::INFINITY }
distances[start] = 0
until nodes.empty?
min_node = nodes.min_by { |node| visited[node] ? Float::INFINITY : distances[node] }
break if distances[min_node] == Float::INFINITY
graph[min_node].each do |neighbor, value|
alt = distances[min_node] + value
distances[neighbor] = alt if alt < distances[neighbor]
end
visited[min_node] = true
nodes.delete(min_node)
end
distances
end
puts dijkstra(graph, 'A')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment