Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Topological Sort

Python Topological Sort

Document Object Reference Manual Python3 Examples

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:

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

)

print

(

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

)

;

print

(

"

Topological sort result:

"

)

g

.

topologicalSort

(

)

The output of the code above is:


Topological sort result:
[5, 4, 2, 3, 1, 0]

Document Object Reference Manual Python3 Examples