Skip to content

Commit fe19524

Browse files
committed
[Feature] Topological sorting for graphs.
1 parent 344ca6e commit fe19524

File tree

3 files changed

+52
-0
lines changed

3 files changed

+52
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ $ coverage report -m
2828
* [Mergesort](sorts/mergesort.py)
2929
* [Radixsort](sorts/radixsort.py)
3030
* [Heapsort](sorts/heapsort.py)
31+
* [Topological Sort](structures/graph.py)
3132

3233
### Searching Algorithms
3334
* [BinarySearch](searches/binary_search.py)

structures/graph.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from collections import defaultdict
2+
13
class GraphNode():
24

35
def __init__(self, val):
@@ -9,3 +11,31 @@ def add_adjacent(self, node):
911

1012
def remove_adjacent(self, node):
1113
self.adjacent_list.remove(node)
14+
15+
class Graph():
16+
17+
def __init__(self, verticies):
18+
self.graph = defaultdict(list)
19+
self.verticies = verticies
20+
21+
def add_edge(self, source, destination):
22+
self.graph[source].append(destination)
23+
24+
def topological_sort(self):
25+
visited = set()
26+
stack = []
27+
28+
def dfs(vertex):
29+
visited.add(vertex)
30+
for i in self.graph[vertex]:
31+
if i not in visited:
32+
dfs(i)
33+
34+
stack.insert(0, vertex)
35+
36+
for i in range(self.verticies):
37+
if i not in visited:
38+
dfs(i)
39+
40+
return stack
41+

tests/test_topological_sort.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import unittest
2+
from structures.graph import Graph
3+
4+
class TestGraphTopoSort(unittest.TestCase):
5+
6+
def test_topological_sort(self):
7+
graph = Graph(6)
8+
graph.add_edge(5,2)
9+
graph.add_edge(5,0)
10+
11+
graph.add_edge(4,0)
12+
graph.add_edge(4,1)
13+
14+
graph.add_edge(2,3)
15+
16+
graph.add_edge(3,1)
17+
18+
self.assertEqual([5, 4, 2, 3, 1, 0], graph.topological_sort())
19+
20+
21+

0 commit comments

Comments
 (0)