Graph
public class Graph{
public void dfs(Vertex u)
{
u.visit();
u.visited = true;
for(each v such that (u,v) belongs E)
{
if(!v.visited){
dfs(v);
}
}
}
public void bfs(Vertex u)
// find shortest path from any vertex to start vertex by following parent pointer.
// this works when the weight of each path is one.
{
u.visit(null);
u.visited = true;
q = new Queue();
q.enqueue(u);
while(q is not empty)
{
v = q.dequeue();
for(each vertex w such that (v, w) is an edge)
{
if(!w.visited)
{w.visit(v); w.visited = true; q.enqueue(w);}
}
}
}
}
public class Vertex{
protected Vertex parent;
protected int depth;
public void visit(Vertex origin){
this.parent = origin;
if(origin == null) this.depth = 0;
else this.depth = origin.depth +1;
}
}

浙公网安备 33010602011771号