简体   繁体   中英

Dijsktra's Shortest Path Algorithm

When I run this, the end output is a table with columns:

Vertex - DisVal - PrevVal - Known.

The two nodes connected to my beginning node show the correct values, but none of the others end up getting updated. I can include the full program code if anyone wants to see, but I know the problem is isolated here. I think it may have to do with not changing the index the right way. This is a simple dijsktra's btw, not the heap/Q version.

Here's the rest of the code: http://ideone.com/UUOUn8

The adjList looks like this: [1: 2, 4, 2: 6, 3, ...] where it shows each node connected to a vertex. DV = distance value (weight), PV = previous value (node), known = has it bee visited

def dijkstras(graph, adjList):
    pv = [None] * len(graph.nodes)
    dv = [999]*len(graph.nodes)
    known = [False] * len(graph.nodes)

    smallestV = 9999
    index = 0
    dv[0] = 0
    known[0] = True
    for i in xrange(len(dv)):
        if dv[i] < smallestV and known[i]:
            smallestV = dv[i]
            index = i
        known[index] = True
        print smallestV
        print index
        for edge in adjList[index]:
            if (dv[index]+graph.weights[(index, edge)] < dv[edge]):
                dv[edge] = dv[index] + graph.weights[(index, edge)]
                pv[edge] = index

    printTable(dv, pv, known)

The first iteration sets smallestV and index to 0 unconditionally, and they never change afterwards (assuming non-negative weights).

Hard to tell what you are trying to do here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM