120 likes | 330 Views
Lab13 . Topological sorting. Problem. For a directed, acyclic graph G=(V,E), f ind a linear ordering of the vertices of V such that for each edge ( i,j ) in E , vertex i is to the left of vertex j . Input . output. Algorithms. L ← Empty list that will contain the sorted elements
E N D
Lab13 Topological sorting
Problem • For a directed, acyclic graph G=(V,E), find a linear ordering of the vertices of V such that for each edge (i,j) in E, vertex i is to the left of vertex j. Input output
Algorithms L ← Empty list that will contain the sorted elements S ← Set of all nodes with no incoming edges while S is non-empty do remove a node n from S insert n into L for each node m with an edge e from n to m do remove edge e from the graph if m has no other incoming edges then insert m into S if graph has edges then output error message (graph has at least one cycle) else output message (proposed topologically sorted order: L)
Example L ← Empty list that will contain the sorted elements S ← Set of all nodes with no incoming edges 0 4 1 2 L: S:0,4 3
while S is non-empty do remove a node n from S insert n into L for each node m with an edge e from n to m do remove edge e from the graph if m has no other incoming edges then insert m into S 0 n 4 e m 1 2 Note: Since S can be simply a set or a queue or a stack. Depending on the order that nodes n is removed from set S, the solution L is not unique. L: 0 S:0,4 3 L: 0 S:0,4,1
while S is non-empty do remove a node n from S insert n into L for each node m with an edge e from n to m do remove edge e from the graph if m has no other incoming edges then insert m into S 0 n 4 e 1 m 2 L: 0 S:4,1 3
while S is non-empty do remove a node n from S insert n into L for each node m with an edge e from n to m do remove edge e from the graph if m has no other incoming edges then insert m into S 0 4 n e 1 m 2 L: 0 S:0,4,1 3 L: 0,4 S:0,4,1 L: 0,4 S:0,4,1,2
while S is non-empty do remove a node n from S insert n into L for each node m with an edge e from n to m do remove edge e from the graph if m has no other incoming edges then insert m into S 0 4 n 1 2 L: 0,4 S: 1,2 e 3 L: 0,4,1 S: 2, ,3 L: 0,4,1 S: 1, 2, m
while S is non-empty do remove a node n from S insert n into L for each node m with an edge e from n to m do remove edge e from the graph if m has no other incoming edges then insert m into S 0 4 n 1 2 L: 0,4,1 S: 2, ,3 3 L: 0,4,1 ,2 S: 2,3
while S is non-empty do remove a node n from S insert n into L for each node m with an edge e from n to m do remove edge e from the graph if m has no other incoming edges then insert m into S 0 4 1 2 L: 0,4,1 ,2 S: 3 3 L: 0,4,1 ,2, 3 S: n
if graph has edges then output error message (graph has at least one cycle) else output message (proposed topologically sorted order: L) 0 4 L: 0,4,1 ,2, 3 S: 1 2 3
L: 0,4,1 ,2, 3 S: 0 4 0 4 1 2 3 1 2 3