Data Structures and Algorithms with Object-Oriented Design Patterns in C#
next up previous contents index

Implementation

Instead of implementing an algorithm that computes a topological sort, we have chosen to implement a traversal that visits the vertices of a DAG in the order given by the topological sort. The topological order traversal can be used to implement many other graph algorithms. Furthermore, given such a traversal, it is easy to define a visitor that computes a topological sort.

In order to implement the algorithm described in the preceding section, an array of integers of length tex2html_wrap_inline70678 is used to record the in-degrees of the vertices. As a result, it is not really necessary to remove vertices or edges from the graph during the traversal. Instead, the effect of removing a vertex and all the edges emanating from that vertex is simulated by decreasing the apparent in-degrees of all the successors of the removed vertex.

In addition, we use a queue to keep track of the vertices that have not yet been visited, but whose in-degree is zero. Doing so eliminates the need to search the array for zero entries.

Program gif defines the TopologicalOrderTraversal method of the AbstractGraph class. This method takes as its argument a Visitor. The Visit method of the visitor is called once for each vertex in the graph. The order in which the vertices are visited is given by a topological sort of those vertices.

   program50348
Program: AbstractGraph class TopologicalOrderTraversal method.

The algorithm begins by computing the in-degrees of all the vertices. An array of integers of length tex2html_wrap_inline70254 called inDegree is used for this purpose. First, all the array elements are set to zero. Then, for each edge tex2html_wrap_inline70988, array element tex2html_wrap_inline70990 is increased by one (lines 12-16). Next, a queue to hold vertices is created. All vertices with in-degree zero are put into this queue (lines 18-21).

The main loop of the TopologicalOrderTraversal method comprises lines 22-31. This loop continues as long as the queue is not empty and the visitor is not finished. In each iteration of the main loop exactly one vertex is dequeued and visited (lines 24-25).

Once a vertex has been visited, the effect of removing that vertex from the graph is simulated by decreasing by one the in-degrees of all the successors of that vertex. When the in-degree of a vertex becomes zero, that vertex is enqueued (lines 26-30).


next up previous contents index

Bruno Copyright © 2001 by Bruno R. Preiss, P.Eng. All rights reserved.