Click here to Skip to main content
14,603,917 members

How do I implement dijkstra's algorithm in Python

Member 14538694 asked:

Open original thread
i want to implement this Dijkstra's pseudocode exactly to my python graph.

Dijkstra's Algorithm DIJKSTRA(G,s,d)  //graph, source, destination   
v ← s //v is always our currently scanned node
    for all n in G.vertices 
       n.tw ← ∞    s.tw ← 0  //Source is no distance from itself
    visited ← []
    while v≠d
         for all vertices, u, adjacent to v
            if v.tw+v[u].w < u.tw
                u.tw ← v.tw+v[u].w
                u.pre ← v         //Store the return path
        visited.append(v)
        min ← ∞        
     for all nodes n ∈ V 
           if n ∉ visited ∧ n.tw < min
                v ← n
                min ← n.tw


What I have tried:

graph = {

'a':{'b':3,'c':4, 'd':7},
'b':{'c':1,'f':5},
'c':{'f':6,'d':2},
'd':{'e':3, 'g':6},
'e':{'g':3, 'h':4},
'f':{'e':1, 'h':8},
'g':{'h':2},
'h':{'g':2}
}


def dijkstra(graph,start,goal):
Tags: Python, algorithms, graph

Preview



When answering a question please:
  1. Read the question carefully.
  2. Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
  3. If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.
  4. Don't tell someone to read the manual. Chances are they have and don't get it. Provide an answer or move on to the next question.
Let's work to help developers, not make them feel stupid.
Please note that all posts will be submitted under the The Code Project Open License (CPOL).




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100