Skip to content

Commit f04970d

Browse files
author
Michael Hammann
committed
feat: added functions to check whether two nodes in a Digraph are connected
1 parent 30a6c02 commit f04970d

File tree

1 file changed

+21
-1
lines changed

1 file changed

+21
-1
lines changed

supervisor/graphutils.py

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
from collections import defaultdict
22

33
class Graph():
4+
""" Class to save and analyse a directed graph
5+
"""
46
def __init__(self,vertices):
57
self.graph = defaultdict(list)
68
self.V = vertices
@@ -9,7 +11,7 @@ def addEdge(self,u,v):
911
self.graph[u].append(v)
1012

1113
def cyclic(self):
12-
"""Return True if the directed graph has a cycle.
14+
""" Return True if the directed graph has a cycle.
1315
The graph must be represented as a dictionary mapping vertices to
1416
iterables of neighbouring vertices. For example:
1517
@@ -34,3 +36,21 @@ def visit(vertex):
3436
return False
3537

3638
return any(visit(v) for v in self.graph)
39+
40+
41+
def connected(self, start_node, end_node):
42+
""" Check whether two nodes are connected, and if the
43+
start_node comes before the end_node.
44+
45+
"""
46+
visited = set()
47+
48+
return self._explore_graph_from(start_node, end_node, visited)
49+
50+
def _explore_graph_from(self, start_node, end_node, visited):
51+
""" Check if end_node comes after start_node and if they are connected
52+
"""
53+
for neighbour in self.graph.get(start_node, ()):
54+
visited.add(neighbour)
55+
self._explore_graph_from(neighbour, end_node, visited)
56+
return end_node in visited

0 commit comments

Comments
 (0)