Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

dijkstras python

"""
This implementation takes in a single source node, and returns a dictionary
of the predecessors. The implementation of print path beneath it returns 
the Dijkstra's algorithm shortest path from the source node, to a target node.
"""

class Graph:
    def __init__(self, graph={}):
        self.graph = graph

	def Dijkstra(self, source):
      dist = {}
      pred = {}
      u = source

      unvisited = set()

      for vertex in self.graph.keys():  # Initializations
        dist[vertex] = sys.maxsize
        unvisited.add(vertex)  # All nodes initially in Q
        pred[vertex] = -1

        dist[source] = 0  # Distance from source to source is set to 0

      while len(unvisited) > 0:  # The main loop

        minDistance = sys.maxsize
        minVertex = source
        for vertex in unvisited:
          if dist[vertex] < minDistance:
            minDistance = dist[vertex]
            minVertex = vertex

            u = minVertex
            unvisited.remove(u)

            for neighborEdge in self.graph[u]:
              w = float(neighborEdge[1])
              v = neighborEdge[0]

              newLength = dist[u] + w

              if newLength < dist[v]:
                dist[v] = newLength
                pred[v] = u
		return pred
        
	def printPath(self, pred, source, target):
        path = [target]
        while path[-1] != source:
            predKey = pred.get(target)
            path.append(predKey)
            target = predKey

        path.reverse()
        # print(path)
        return path
Comment

PREVIOUS NEXT
Code Example
Python :: print python float precision 
Python :: python b string 
Python :: how to read panda column 
Python :: pandas data frame to list 
Python :: python loop opening file from directory 
Python :: dir() in python 
Python :: default orange and blue matplotlib 
Python :: django-sslserver 
Python :: word embedding python 
Python :: matplotlib vertical tick labels 
Python :: how to get count by using group by in python 
Python :: python see if a number is greater than other 
Python :: jupyter notebook plot background dark theme 
Python :: python concatenate lists 
Python :: multiprocessing print does not work 
Python :: how to prepare independent and dependent variables from dataframe 
Python :: import ImageGrab 
Python :: remove in list python 
Python :: how to save dataframe as csv in python 
Python :: print colored text in python 
Python :: spacy tokineze stream 
Python :: prevent division by zero numpy 
Python :: select pandas by t dtype python 
Python :: how to make a function in python 
Python :: pandas replace last cell 
Python :: Python - Change List Items 
Python :: how to create a dictionary in python 
Python :: Check if the url is reachable or not in Python 
Python :: url encoded path using python 
Python :: list to dict python with same values 
ADD CONTENT
Topic
Content
Source link
Name
1+7 =