Created
January 27, 2018 15:52
-
-
Save mgronhol/0de604cea70b6c7d102c53a52c0b4563 to your computer and use it in GitHub Desktop.
Dijkstra's algorithm
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python2.7 | |
| nodes = ["A", "B", "C", "D"] | |
| conns = {} | |
| conns["A"] = {"B": 2, "C": 1} | |
| conns["B"] = {"C": 1, "D": 2} | |
| conns["C"] = {"D": 1} | |
| conns["D"] = {} | |
| def dijkstra( nodes, conns, source, target ): | |
| dist = {} | |
| prev = {} | |
| # alustetaan haku | |
| unvisited = [] | |
| for node in nodes: | |
| dist[node] = 1e99 | |
| prev[node] = None | |
| unvisited.append( node ) | |
| dist[source] = 0.0 | |
| found_target = False | |
| while len( unvisited ) > 0 and not found_target: | |
| current = unvisited[0] | |
| # etitaan unvisited node, jolla on pienin dist | |
| for node in unvisited: | |
| if dist[node] < dist[current]: | |
| current = node | |
| unvisited.remove( current ) | |
| # ollaanko perilla | |
| if current == target: | |
| found_target = True | |
| # kaydaan lapi kaikki nodet, jotka on nykyisen noden naapureita | |
| for next_node in conns[current]: | |
| #lasketaan etaisyys | |
| hop_distance = conns[current][next_node] | |
| total_distance = dist[current] + hop_distance | |
| # jos loydettiin patka lyhyempaa reittia, otetaan se talteen | |
| if total_distance < dist[next_node]: | |
| dist[next_node] = total_distance | |
| prev[next_node] = current | |
| # paristaan tuloksista se reitti | |
| polku = [] | |
| current = target | |
| while prev[current] is not None: | |
| polku.append( current ) | |
| current = prev[current] | |
| polku.append( source ) | |
| polku.reverse() | |
| return polku | |
| print dijkstra( nodes, conns, "A", "D" ) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment