Prim's Algorithm


public void prim( Vertex s ) {
  for ( Vertex v : vertices ) {
    v.visited = false;
    v.parent = null;
    v.cost = 999999; }
  s.cost = 0;
  PriorityQueue<Vertex>
      fringe = new PriorityQueue<Vertex>(20,
        new Comparator<Vertex>() {
          public int compare(Vertex i, Vertex j) {
              return (i.cost - j.cost); }});
  fringe.add(s);
  while ( ! fringe.isEmpty() ) {
    Vertex v = fringe.remove();  // lowest-cost
    if ( ! v.visited )
      { v.visited = true;
        for ( Edge e : v.edges )
          {  if ( (! e.target.visited) &&
                  ( e.cost < e.target.cost ) )
             { e.target.cost = e.cost;
               e.target.parent = v;
               fringe.add(e.target); } } } } }

Contents    Page-10    Prev    Next    Page+10    Index