1
1
from collections import defaultdict
2
2
3
3
class Graph ():
4
+ """ Class to save and analyse a directed graph
5
+ """
4
6
def __init__ (self ,vertices ):
5
7
self .graph = defaultdict (list )
6
8
self .V = vertices
@@ -9,7 +11,7 @@ def addEdge(self,u,v):
9
11
self .graph [u ].append (v )
10
12
11
13
def cyclic (self ):
12
- """Return True if the directed graph has a cycle.
14
+ """ Return True if the directed graph has a cycle.
13
15
The graph must be represented as a dictionary mapping vertices to
14
16
iterables of neighbouring vertices. For example:
15
17
@@ -34,3 +36,21 @@ def visit(vertex):
34
36
return False
35
37
36
38
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