From 75c4e45f9d86ca45658bcd8dcece272521bc7701 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bertrand=20N=C3=A9ron?= <bneron@pasteur.fr> Date: Mon, 9 Sep 2019 17:17:25 +0200 Subject: [PATCH] :sparkles: add dikjstra algo --- Graph/graph/traversing.py | 43 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/Graph/graph/traversing.py b/Graph/graph/traversing.py index 07f7da4..3d66df1 100644 --- a/Graph/graph/traversing.py +++ b/Graph/graph/traversing.py @@ -65,3 +65,46 @@ def BFS(graph: Graph, node: Node) -> Iterator[Tuple[Node, List[Edge]]]: :return: """ return _traversing(LIFO(), graph, node) + + +def Dikjstra(graph, start_node, target_node): + to_visit = LIFO() + to_visit.add(start_node) + visited = set() + parent = {} + ########################## + # graph traversing + ########################## + path = [] + rank = 0 + while to_visit: + rank += 1 + node = to_visit.pop() + # it is important to add node in visited right now + # and not a the end of the block + # otherwise node is not anymore in to_visit and not yet in visited + # so when we explore neighbors we add it again in to_visit + visited.add(node) + for edge in graph.edges(node): + if edge.target not in visited and edge.target not in to_visit: + edge['rank'] = rank + parent[edge.target] = edge + to_visit.add(edge.target) + + + ########################### + # find paths + ########################### + def find_parent(graph, node, rank, path): + path = [] + nbh = [e.target for e in graph.edges(node) if e.rank == rank] + path.append(nbh[0]) + if nbh[0] != start_node: + find_parent(graph, nbh[0], rank - 1, path) + return path + + rank = min([e.rank for e in graph.edges(target_node)]) + paths = find_parent(graph, target_node, rank, []) + return paths + + -- GitLab