23.11.2014 Views

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Justification: The <strong>in</strong>itial computation of <strong>in</strong>-degrees <strong>and</strong> setup of the<br />

<strong>in</strong>counter variables can be done with a simple traversal of the graph, which takes<br />

O(n + m) time. We use the decorator pattern to associate counter attributes with the<br />

vertices. Say that a vertex u is visited by the topological sort<strong>in</strong>g algorithm when u is<br />

removed from the stack S. A vertex u can be visited only when <strong>in</strong>counter (u) = 0,<br />

which implies that all its predecessors (vertices with outgo<strong>in</strong>g edges <strong>in</strong>to u) were<br />

previously visited. As a consequence, any vertex that is on a directed cycle will<br />

never be visited, <strong>and</strong> any other vertex will be visited exactly once. The algorithm<br />

traverses all the outgo<strong>in</strong>g edges of each visited vertex once, so its runn<strong>in</strong>g time is<br />

proportional to the number of outgo<strong>in</strong>g edges of the visited vertices. Therefore, the<br />

algorithm runs <strong>in</strong> O(n + m) time. Regard<strong>in</strong>g the space usage, observe that the stack<br />

S <strong>and</strong> the <strong>in</strong>counter variables attached to the vertices use O(n) space.<br />

As a side effect, the topological sort<strong>in</strong>g algorithm of Code Fragment 13.13 also tests<br />

whether the <strong>in</strong>put digraph is acyclic. Indeed, if the algorithm term<strong>in</strong>ates without<br />

order<strong>in</strong>g all the vertices, then the subgraph of the vertices that have not been<br />

ordered must conta<strong>in</strong> a directed cycle.<br />

Figure 13.12: Example of a run of algorithm<br />

TopologicalSort (Code Fragment 13.13): (a) <strong>in</strong>itial<br />

configuration; (b-i) after each while-loop iteration. The<br />

vertex labels show the vertex number <strong>and</strong> the current<br />

<strong>in</strong>counter value. The edges traversed are shown with<br />

dashed blue arrows. Thick l<strong>in</strong>es denote the vertex <strong>and</strong><br />

edges exam<strong>in</strong>ed <strong>in</strong> the current iteration.<br />

839

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!