Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added new folder of Evolutionary Algorithms Folder #203

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
107 changes: 42 additions & 65 deletions Graph_Algorithms/src/Dijkstra/Dijkstra.py
Original file line number Diff line number Diff line change
@@ -1,68 +1,45 @@
from collections import defaultdict
import math

class Graph:
def __init__(self):
self.nodes = set()
self.archs = defaultdict(list)
self.values = {}

def add_node(self, value):
self.nodes.add(value)

def add_edge(self, init_node, final_node, value):
self.archs[init_node].append(final_node)
self.archs[init_node].append(final_node)
self.values[(init_node, final_node)] = value


def dijkstra(graph, initial):
visited = {initial: 0}

nodes = set(graph.nodes)

while nodes:
min_node = None
for node in nodes:
if node in visited:
if min_node is None:
min_node = node
elif visited[node] < visited[min_node]:
min_node = node
"""Dijkstra's algorithm."""

if min_node is None:
break

nodes.remove(min_node)
current_weight = visited[min_node]

for arch in graph.archs[min_node]:
try:
weight = current_weight + graph.values[(min_node, arch)]
except:
weight = current_weight + math.inf
if arch not in visited or weight < visited[arch]:
visited[arch] = weight

return visited


def main():

#initializing values
g = Graph()
g.add_node('a')
g.add_node('b')
g.add_node('c')
g.add_node('d')

g.add_edge('a', 'b', 10)
g.add_edge('b', 'c', 2)
g.add_edge('a', 'c', 1)
g.add_edge('c', 'd', 1)
g.add_edge('b', 'd', 8)
import math

#output
print(dijkstra(g, 'a'))

main()
class Vertex:

def __init__(self, id):
self.id = str(id)
self.distance = 0
self.neighbors = []
self.edges = {} # {vertex:distance}

def __lt__(self, other):
"""Comparison rule to < operator."""
return self.distance < other.distance

def __repr__(self):
"""Return the vertex id."""
return self.id

def add_neighbor(self, vertex):
"""Add a pointer to a vertex at neighbor's list."""
self.neighbors.append(vertex)

def add_edge(self, vertex, weight):
"""Destination vertex and weight."""
self.edges[vertex.id] = weight


def dijkstra(graph, source, destiny):
"""Dijkstra's Algorithm."""
q = []
for v in graph:
v.distance = math.inf
q.append(v)
source.distance = 0
while q:
v = min(q)
q.remove(v)
for u in v.neighbors:
new = v.distance + v.edges[u.id]
if new < u.distance:
u.distance = new
return destiny.distance
Loading