11from collections import defaultdict
22
33class 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