Kruskal's algorithm for spanning tree

Another popular algorithm for finding a minimum spanning tree is Kruskal's algorithm. It is similar to Prim's algorithm and uses a greedy approach to find the solution. Here are the steps we need to implement Kruskal's algorithm:

  1. Create a forest T (a set of trees), where each vertex in the graph is a separate tree.
  2. Create a set S containing all the edges in the graph.
  3. While S is non-empty and T is not yet spanning:

1. Remove an edge with the minimum weight from S.

2. If that edge connects two different trees, then add it to the forest, combining two trees into a single tree; otherwise, discard that edge.

We will use the same graph that we used for Prim's algorithm. Here is the implementation of Kruskal's algorithm:

function Kruskal(array $graph): array { 
$len = count($graph);
$tree = [];

$set = [];
foreach ($graph as $k => $adj) {
$set[$k] = [$k];
}

$edges = [];
for ($i = 0; $i < $len; $i++) {
for ($j = 0; $j < $i; $j++) {
if ($graph[$i][$j]) {
$edges[$i . ',' . $j] = $graph[$i][$j];
}
}
}

asort($edges);

foreach ($edges as $k => $w) {
list($i, $j) = explode(',', $k);

$iSet = findSet($set, $i);
$jSet = findSet($set, $j);
if ($iSet != $jSet) {
$tree[] = ["from" => $i, "to" => $j,
"cost" => $graph[$i][$j]];
unionSet($set, $iSet, $jSet);
}
}

return $tree;
}

function findSet(array &$set, int $index) {
foreach ($set as $k => $v) {
if (in_array($index, $v)) {
return $k;
}
}

return false;
}

function unionSet(array &$set, int $i, int $j) {
$a = $set[$i];
$b = $set[$j];
unset($set[$i], $set[$j]);
$set[] = array_merge($a, $b);
}

As we can see, we have two separate functions—unionSet and findSet—to perform the union operations of two disjointed sets, as well as find out whether a number exists in a set or not. Now, let's run the program with our constructed graph like this:

$graph = [ 
[0, 3, 1, 6, 0, 0],
[3, 0, 5, 0, 3, 0],
[1, 5, 0, 5, 6, 4],
[6, 0, 5, 0, 0, 2],
[0, 3, 6, 0, 0, 6],
[0, 0, 4, 2, 6, 0]
];

$mst = Kruskal($graph);

$minimumCost = 0;

foreach($mst as $v) {
echo "From {$v['from']} to {$v['to']} cost is {$v['cost']} ";
$minimumCost += $v['cost'];
}

echo "Minimum cost: $minimumCost ";

This will produce the following output, which is similar to our output from Prim's algorithm:

From 2 to 0 cost is 1
From 5 to 3 cost is 2
From 1 to 0 cost is 3
From 4 to 1 cost is 3
From 5 to 2 cost is 4
Minimum cost: 13

The complexity of Kruskal's algorithm is O (E log V), which is better than the generic implementation of Prim's algorithm.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset