Problem: Find all the vertices connected to a given vertex.
Class:
public class DepthFirstSearch
{
private boolean[] marked;
private int count;
public DepthFirstSearch(Graph G, int s)
{
marked = new boolean[G.V()];
dfs(G, s);
}
private void dfs(Graph G, int v)
{
marked[v] = true;
count++;
for (int w : G.adj(v))
if (!marked[w]) dfs(G, w);
}
public boolean marked(int w)
{ return marked[w]; }
public int count()
{ return count; }
}
Is vertex v is connected to s in graph G?
DepthFirstSearch g = new DepthFirstSearch(G, s);
boolean answer = g.marked(w);