コード例 #1
0
ファイル: Application11.php プロジェクト: EdenChan/Instances
 /**
  * Weighted graph test program.
  *
  * @param object IGraph $g The weighted graph to test.
  */
 public static function weightedGraphTest(IGraph $g)
 {
     printf("Weighted graph test program.\n");
     $g->addVertex(0, box(123));
     $g->addVertex(1, box(234));
     $g->addVertex(2, box(345));
     $g->addEdge(0, 1, box(3));
     $g->addEdge(0, 2, box(1));
     $g->addEdge(1, 2, box(4));
     printf("%s\n", str($g));
     printf("Prim's Algorithm\n");
     $g2 = Algorithms::primsAlgorithm($g, 0);
     printf("%s\n", str($g2));
     printf("Kruskal's Algorithm\n");
     $g2 = Algorithms::kruskalsAlgorithm($g);
     printf("%s\n", str($g2));
 }
コード例 #2
0
ファイル: AbstractGraph.php プロジェクト: EdenChan/Instances
 /**
  * Weighted graph test method.
  *
  * @param object IGraph $g The weighted graph to test.
  */
 public static function testWeighted(IGraph $g)
 {
     printf("Weighted graph test program.\n");
     $g->addVertex(0, box(123));
     $g->addVertex(1, box(234));
     $g->addVertex(2, box(345));
     $g->addEdge(0, 1, box(3));
     $g->addEdge(0, 2, box(1));
     $g->addEdge(1, 2, box(4));
     printf("%s\n", str($g));
     printf("Using vertex iterator\n");
     foreach ($g->getVertices() as $v) {
         printf("%s\n", str($v));
     }
     printf("Using edge iterator\n");
     foreach ($g->getEdges() as $e) {
         printf("%s\n", str($e));
     }
 }
コード例 #3
0
ファイル: Algorithms.php プロジェクト: EdenChan/Instances
 /**
  * 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;
 }