From f04970d5e471928103568cfa885424777151d443 Mon Sep 17 00:00:00 2001 From: Michael Hammann Date: Thu, 9 Dec 2021 16:36:22 +0100 Subject: [PATCH] feat: added functions to check whether two nodes in a Digraph are connected --- supervisor/graphutils.py | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/supervisor/graphutils.py b/supervisor/graphutils.py index 867f3aa06..af70add6b 100644 --- a/supervisor/graphutils.py +++ b/supervisor/graphutils.py @@ -1,6 +1,8 @@ from collections import defaultdict class Graph(): + """ Class to save and analyse a directed graph + """ def __init__(self,vertices): self.graph = defaultdict(list) self.V = vertices @@ -9,7 +11,7 @@ def addEdge(self,u,v): self.graph[u].append(v) def cyclic(self): - """Return True if the directed graph has a cycle. + """ Return True if the directed graph has a cycle. The graph must be represented as a dictionary mapping vertices to iterables of neighbouring vertices. For example: @@ -34,3 +36,21 @@ def visit(vertex): return False return any(visit(v) for v in self.graph) + + + def connected(self, start_node, end_node): + """ Check whether two nodes are connected, and if the + start_node comes before the end_node. + + """ + visited = set() + + return self._explore_graph_from(start_node, end_node, visited) + + def _explore_graph_from(self, start_node, end_node, visited): + """ Check if end_node comes after start_node and if they are connected + """ + for neighbour in self.graph.get(start_node, ()): + visited.add(neighbour) + self._explore_graph_from(neighbour, end_node, visited) + return end_node in visited