Skip to content

Commit 3e1d1a5

Browse files
committed
[Documentation] Added documentation for topological sorting.
1 parent fe19524 commit 3e1d1a5

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

structures/graph.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,15 +13,48 @@ def remove_adjacent(self, node):
1313
self.adjacent_list.remove(node)
1414

1515
class Graph():
16+
"""
17+
A directed graph represented with an adjacency list.
18+
"""
1619

1720
def __init__(self, verticies):
1821
self.graph = defaultdict(list)
1922
self.verticies = verticies
2023

2124
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+
"""
2236
self.graph[source].append(destination)
2337

2438
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+
"""
2558
visited = set()
2659
stack = []
2760

0 commit comments

Comments
 (0)