'dijkstra's algorithm how do you set values to infinity? [duplicate]
Hi im wroking on dijkstra's algorithm and the first hint in the comments is, '''For all the nodes in the graph, set distance equal to infinity and previous equal to none ''' What does he mean by this how do you set the values equal to infinity?Also in the method there is not end so im guessing just to make the end the adjacent node ? Im saying this because there is a are_adjacent method This is the little i have
def are_adjacent(self, value1, value2):
return(self.find(value1).is_adjacent(self.find(value2)))
def dijkstra(self, start):
Solution 1:[1]
You can set a value as infinite:
value = float('inf')
Or in python 3.5:
import math
value = math.inf
Solution 2:[2]
You can do like this in Python:
var = float('inf')
var = float('-inf') # for minus oo
With python >= 3.5 using the math module: (as @alpert and @YOU pointed out in the comments)
import math
var = math.inf
var = -math.inf
Solution 3:[3]
- You can set it to some big value something like 1e9 (NodeCount * MaximumEdgeWeight, there will be no path more than such value);
- Or set it to value "-1" and check it with some "if": if(d[v] == -1) {/* Then it is infinity */}.
Solution 4:[4]
you can have the dictionary to have all the nodes in the graph as keys and their respective known distances as values, which you will keep on updating and will return it eventually E.g. {'A':0, 'B':3, 'C':5, 'D': 7}
Now, coming on your question that how to set distance to infinity as indeed the distance to all other nodes from the source is unknown initially, therefore set the initial distance to infinity. The following code would do the trick:
result = {}
result[source] = 0 # as the Distance from source to source itself is 0
for node in graph.nodes:
if (node != source):
result[node] = sys.maxsize
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | |
| Solution 3 | 107th |
| Solution 4 | mudassir ahmed |
