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.

levels. BFS can also be thought of as a traversal us<strong>in</strong>g a str<strong>in</strong>g <strong>and</strong> pa<strong>in</strong>t, with BFS<br />

unroll<strong>in</strong>g the str<strong>in</strong>g <strong>in</strong> a more conservative manner.<br />

BFS starts at vertex s, which is at level 0 <strong>and</strong> def<strong>in</strong>es the "anchor" for our str<strong>in</strong>g. In<br />

the first round, we let out the str<strong>in</strong>g the length of one edge <strong>and</strong> we visit all the<br />

vertices we can reach without unroll<strong>in</strong>g the str<strong>in</strong>g any farther. In this case, we visit,<br />

<strong>and</strong> pa<strong>in</strong>t as "visited," the vertices adjacent to the start vertex s—these vertices are<br />

placed <strong>in</strong>to level 1. In the second round, we unroll the str<strong>in</strong>g the length of two edges<br />

<strong>and</strong> we visit all the new vertices we can reach without unroll<strong>in</strong>g our str<strong>in</strong>g any<br />

farther. These new vertices, which are adjacent to level 1 vertices <strong>and</strong> not<br />

previously assigned to a level, are placed <strong>in</strong>to level 2, <strong>and</strong> so on. The BFS traversal<br />

term<strong>in</strong>ates when every vertex has been visited.<br />

Pseudo-code for a BFS start<strong>in</strong>g at a vertex s is shown <strong>in</strong> Code Fragment 13.10. We<br />

use auxiliary space to label edges, mark visited vertices, <strong>and</strong> store collections<br />

associated with levels. That is, the collections L 0 , L 1 , L 2 , <strong>and</strong> so on, store the<br />

vertices that are <strong>in</strong> level 0, level 1, level 2, <strong>and</strong> so on. These collections could, for<br />

example, be implemented as queues. They also allow BFS to be nonrecursive.<br />

Code Fragment 13.10: The BFS algorithm.<br />

We illustrate a BFS traversal <strong>in</strong> Figure 13.7.<br />

823

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

Saved successfully!

Ooh no, something went wrong!