# Djikstras Algorithm

``````
class Graph:

def __init__(self, Nodes, is_directed = False):
self.nodes = Nodes

self.is_directed = is_directed

for node in self.nodes:

if not self.is_directed:

def __len__(self):
return len(nodes)

def __getitem__(self,node):

"""retrives items from out Node/vertex"""

def __iter__(self):

def degree(self,node):
'''Total number of edges coming out a given node'''
return deg

for node in self.nodes:

``````

Letâ€™s add some Nodes(Vertex), Edges, and the weights to our Graph!

``````
all_edges = [

("A","B", 4),("A","C", 1),("B","D", 1),("C","D", 5),
("C","B", 2),("D","E",3)
]

nodes = ["A","B","C","D","E"]

graph1 = Graph(nodes)

for u,v,w in all_edges:

``````
``````

``````

Graph Printed with Edges and Weights

``````A -> {'B': 4, 'C': 1}
B -> {'A': 4, 'D': 1, 'C': 2}
C -> {'A': 1, 'D': 5, 'B': 2}
D -> {'B': 1, 'C': 5, 'E': 3}
E -> {'D': 3}

``````
``````

import heapq

def Dijkstras(graph, starting_vertex):
distances = {}
distances = {vertex: float('infinity') for vertex in graph}

distances[starting_vertex] = 0

pq = [(0, starting_vertex)]

while len(pq) > 0:

current_distance, current_vertex = heapq.heappop(pq)

if current_distance > distances[current_vertex]:
continue

for neighbor, weight in graph[current_vertex].items():
distance = current_distance + weight

if distance < distances[neighbor]:
distances[neighbor] = distance

heapq.heappush(pq, (distance, neighbor))

return distances

``````
``````
Dijkstras(graph1, "A")

``````

Distance from Vertex A

``````
{'A': 0, 'B': 3, 'C': 1, 'D': 4, 'E': 7}

``````