简体   繁体   中英

dijkstra's algorithm with shortest path

Can Someone help me or point me in the right direction im just lost i dont know what they mean set values to infinity are they talking about the edges? or is this a new variable that each node has.Some advice or some help being pointed in the right direction would be appreciated. Heres what i have so far (though its garbage in my opinion)

def dijkstra(self, start):

    print("end dijkstra")
    for node in self.__nodes:
            curr_node = 0
            for node in self.__nodes:
                distances = float('inf')
                before_node = None

                print(node)

    """
    try:


        #for node in weighted_digraph:
            #distances[node] = float('inf')
            #predecessors[node] = None
            print("work")
            print(node)
            #print(weighted_digraph)
        #sp_set = []
        #distances[start] = 0
    except TypeError:
        print("BS OCCURED")
    """

So initially, you have no idea how far away each node is from the source (in fact, they may not all be reachable at all in the case that your graph is not connected!). This "set to infinity" business has to do with the shortest-known distance from the source node to each of the nodes. Each of your nodes needs to know how far away from the source they are, and initially that value is infinity (because you haven't walked along any edges to enumerate a path to them).

To set variables values to infinity, use:

var = float('inf')

The reason to do this is usually when you want to find the minimum in an optimization function; setting a value to infinity allows to compare it to any other value and be sure that the other will be lower.

In a maximization problem you can set values to minus infinity at the start like this:

var = float('-inf')

in python > 3.5, you cna also use the math module:

var = math.inf
var = -math.inf

what they mean set values to infinity are they talking about the edges?

No, they are talking about the distance of a node that you are going to execute Dijkstra on to every other nodes. Since you initially what the shortest distance is, let's put it as infinite.

Here is an example of how you can initialize it (in pseudo code):

for each vertex v in Graph:
    dist[v] ← INFINITY
    prev[v] ← UNDEFINED // Previous node in optimal path from source

dist[source] ← 0 //distance from a node to itself is zero.

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