Skip to content

Commit addf920

Browse files
committed
Add topological sorter
1 parent 672ec7a commit addf920

File tree

3 files changed

+51
-0
lines changed

3 files changed

+51
-0
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,3 +4,5 @@
44
| -- | -- |
55
|[Signature parser](create_electronic_sign) | Parse handwritten signature in JPG/JPEG/PNG to a new JPG with black signature and transparent background. |
66
|[2-opt TSP](2-opt-tsp) | Find local minimum weighted Hamiltonian cycle in a complete graph expressed with a cost adjacency matrix. |
7+
|[Topological sorter](topological_sorter) | From a directed graph, find a topologically ordered list of vertices. |
8+
|[Connected components graph](scc-graph) | From a directed graph, return a graph with sets as vertices. |

topological_sorter/README.md

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
## Topological sorter
2+
3+
Input: a directed graph
4+
```
5+
Enter an edge, eg.: A->B
6+
a->b
7+
Enter an edge, eg.: A->B
8+
b->c
9+
Enter an edge, eg.: A->B
10+
j->a
11+
Enter an edge, eg.: A->B
12+
# blank line to finish
13+
```
14+
15+
Output: an ordered list
16+
```
17+
Directed graph constructed.
18+
Topologically sorted: ['j', 'a', 'b', 'c']
19+
```
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
from collections import defaultdict
2+
from typing import DefaultDict
3+
4+
def topological_sort(graph, node):
5+
ret = []
6+
visited = set()
7+
8+
def rec(node):
9+
visited.add(node)
10+
for neighbour in graph[node]:
11+
if neighbour not in visited:
12+
visited.add(neighbour)
13+
rec(neighbour)
14+
ret.insert(0, node)
15+
# check all keys in graph are visited
16+
for k in list(graph):
17+
if k not in visited:
18+
rec(k)
19+
return ret
20+
21+
if __name__ == '__main__':
22+
graph = defaultdict(set) # string to set of strings
23+
while True:
24+
edge = input("Enter an edge, eg.: A->B \n").strip().split("->")
25+
if len(edge) == 2:
26+
graph[edge[0]].add(edge[1])
27+
else:
28+
print("Directed graph constructed.")
29+
break
30+
print("Topologically sorted: ", topological_sort(graph, next(iter(graph))))

0 commit comments

Comments
 (0)