Last active
August 29, 2015 14:18
-
-
Save yukpiz/53a4c260fffe959904aa to your computer and use it in GitHub Desktop.
Dijkstra algorithm.
This file contains 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
nodes = { | |
"A": ["", ""], | |
"B": ["", ""], | |
"C": ["", ""], | |
"D": ["", ""], | |
} | |
connects = [ | |
["A", "B", "10"], | |
["B", "C", "10"], | |
["C", "D", "10"], | |
["A", "D", "31"], | |
] | |
start = "A" | |
goal = "D" | |
def initStart(start): | |
nodes[start] = [start, 0] | |
def nodeTo(base): | |
loopCount = 0 | |
for connect in connects: | |
loopCount += 1 | |
if connect[0] == base: | |
target = connect[1] | |
currentCost = int(nodes[base][1]) | |
rootCost = int(connect[2]) | |
if nodes[target][0] == "" or int(nodes[target][1]) > currentCost + rootCost: | |
nodes[target][0] = base | |
nodes[target][1] = str(currentCost + rootCost) | |
loopCount += nodeTo(target) | |
return loopCount | |
initStart(start) | |
print nodeTo(start) | |
print nodes | |
print "=" * 30 | |
print nodes[goal][1] | |
print "=" * 30 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment