Skip to content

Commit

Permalink
feat: added functions to check whether two nodes in a Digraph are con…
Browse files Browse the repository at this point in the history
…nected
  • Loading branch information
Michael Hammann committed Apr 13, 2022
1 parent 30a6c02 commit f04970d
Showing 1 changed file with 21 additions and 1 deletion.
22 changes: 21 additions & 1 deletion supervisor/graphutils.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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:
Expand All @@ -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

0 comments on commit f04970d

Please sign in to comment.