Python Topological Sort
A topological sort of a directed acyclic graph (DAG) G arranges all the vertices of G into a linear sequence such that for any pair of vertices u and v, if the edge (u,v) is in E(G), then u appears before v in the linear sequence. Such a linear sequence is usually called a sequence satisfying a topological order, or simply a topological sequence. Simply put, deriving a total order on a set from a partial order on that set is called topological sorting.
In graph theory, a sequence of the vertices of a directed acyclic graph is called a topological sort of that graph if and only if the following conditions are met:
- Each vertex appears exactly once;
- If A appears before B in the sequence, then there is no path from B to A in the graph.
Example
from
collections
import
defaultdict
class
Graph
:
def
init
(
self
,
vertices
)
:
self
.
graph
=
defaultdict
(
list
)
self
.
V
=
vertices
def
addEdge
(
self
,
u
,
v
)
:
self
.
graph
[
u
]
.
append
(
v
)
def
topologicalSortUtil
(
self
,
v
,
visited
,
stack
)
:
visited
[
v
]
=
True
for
i
in
self
.
graph
[
v
]
:
if
visited
[
i
]
==
False
:
self
.
topologicalSortUtil
(
i
,
visited
,
stack
)
stack
.
insert
(
0
,
v
)
def
topologicalSort
(
self
)
:
visited
=
[
False
]
self
.
V
stack
=
[
]
for
i
in
range
(
self
.
V
)
:
if
visited
[
i
]
==
False
:
self
.
topologicalSortUtil
(
i
,
visited
,
stack
)
(
stack
)
g
=
Graph
(
6
)
g
.
addEdge
(
5
,
2
)
;
g
.
addEdge
(
5
,
0
)
;
g
.
addEdge
(
4
,
0
)
;
g
.
addEdge
(
4
,
1
)
;
g
.
addEdge
(
2
,
3
)
;
g
.
addEdge
(
3
,
1
)
;
(
"
Topological sort result:
"
)
g
.
topologicalSort
(
)
The output of the code above is:
Topological sort result:
[5, 4, 2, 3, 1, 0]
Python3 Examples