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;    

  }

}

posted @ 2014-12-28 10:07  新一代的天皇巨星  阅读(149)  评论(0)    收藏  举报