@@ -13,15 +13,48 @@ def remove_adjacent(self, node):
13
13
self .adjacent_list .remove (node )
14
14
15
15
class Graph ():
16
+ """
17
+ A directed graph represented with an adjacency list.
18
+ """
16
19
17
20
def __init__ (self , verticies ):
18
21
self .graph = defaultdict (list )
19
22
self .verticies = verticies
20
23
21
24
def add_edge (self , source , destination ):
25
+ """
26
+ Add an edge to the graph.
27
+
28
+ Add an edge pointing from source vertex
29
+ to destination vertex.
30
+
31
+ Args:
32
+ source: the source vertex
33
+ destination: the destination vertex
34
+
35
+ """
22
36
self .graph [source ].append (destination )
23
37
24
38
def topological_sort (self ):
39
+ """
40
+ Sort the graph topologically.
41
+
42
+ A topological sort lists nodes in such a way
43
+ that every node 's' in 's' -> 'd' directed pairs
44
+ is listed before 'd.' This will not work in a
45
+ graph that contains cycles.
46
+
47
+ The algorithm looks at every node, and does a
48
+ dfs for each node adjacent to the node and then adds
49
+ the originating node to a stack. In the end, the stack
50
+ will be in order of a possible topological sort.
51
+
52
+ Topological sorts are not necessarily unique.
53
+
54
+ Returns:
55
+ A list of vertices in a topological ordering.
56
+
57
+ """
25
58
visited = set ()
26
59
stack = []
27
60
0 commit comments