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.

Us<strong>in</strong>g the Template Method Pattern for DFS<br />

The DFS class is based on the template method pattern (see Section 7.3.7), which<br />

describes a generic computation mechanism that can be specialized by redef<strong>in</strong><strong>in</strong>g<br />

certa<strong>in</strong> steps. The way we identify vertices <strong>and</strong> edges that have already been<br />

visited dur<strong>in</strong>g the traversal is <strong>in</strong> calls to methods isVisited, visit, <strong>and</strong><br />

unVisit. For us to do anyth<strong>in</strong>g <strong>in</strong>terest<strong>in</strong>g, we must extend DFS <strong>and</strong> redef<strong>in</strong>e<br />

some of its auxiliary methods. This approach conforms to the template method<br />

pattern. In Code Fragments 13.6 through 13.9, we illustrate some applications of<br />

DFS traversal.<br />

Class ConnectivityDFS (Code Fragment 13.6) tests whether the graph is<br />

connected. It counts the vertices reachable by a DFS traversal start<strong>in</strong>g at a vertex<br />

<strong>and</strong> compares this number with the total number of vertices of the graph.<br />

Code Fragment 13.6: Specialization of class DFS to<br />

test if a graph is connected.<br />

Class ComponentsDFS (Code Fragment 13.7) f<strong>in</strong>ds the connected components<br />

of a graph. It labels each vertex with its connected component number, us<strong>in</strong>g the<br />

decorator pattern, <strong>and</strong> returns the number of connected components found.<br />

Code Fragment 13.7: Specialization of DFS to<br />

compute connected components.<br />

819

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

Saved successfully!

Ooh no, something went wrong!