Skip to content

Instantly share code, notes, and snippets.

@yukpiz
Last active August 29, 2015 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yukpiz/53a4c260fffe959904aa to your computer and use it in GitHub Desktop.
Save yukpiz/53a4c260fffe959904aa to your computer and use it in GitHub Desktop.
Dijkstra algorithm.
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