Пример #1
0
 /**
  * Kruskal's algorithm to find a minimum-cost spanning tree
  * for the given edge-weighted, undirected graph.
  * Uses a partition and a priority queue.
  *
  * @param object IGraph $g An edge-weighted, undirected graph.
  * It is assumed that the edge weights are <code>Int</code>s
  * @return object IGraph An unweighted, undirected graph that represents
  * the minimum-cost spanning tree.
  */
 public static function kruskalsAlgorithm(IGraph $g)
 {
     $n = $g->getNumberOfVertices();
     $result = new GraphAsLists($n);
     for ($v = 0; $v < $n; ++$v) {
         $result->addVertex($v);
     }
     $queue = new BinaryHeap($g->getNumberOfEdges());
     foreach ($g->getEdges() as $edge) {
         $weight = $edge->getWeight();
         $queue->enqueue(new Association($weight, $edge));
     }
     $partition = new PartitionAsForest($n);
     while (!$queue->isEmpty() && $partition->getCount() > 1) {
         $assoc = $queue->dequeueMin();
         $edge = $assoc->getValue();
         $n0 = $edge->getV0()->getNumber();
         $n1 = $edge->getV1()->getNumber();
         $s = $partition->findItem($n0);
         $t = $partition->findItem($n1);
         if ($s !== $t) {
             $partition->join($s, $t);
             $result->addEdge($n0, $n1);
         }
     }
     return $result;
 }