• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

PHP实现克鲁斯卡尔算法实例解析_php技巧

php 搞代码 4年前 (2022-01-26) 33次浏览 已收录 0个评论

本文实例展示了PHP实现的格鲁斯卡尔算法(kruscal)的实现方法,分享给大家供大家参考。相信对于大家的PHP程序设计有一定的借鉴价值。

具体代码如下:

 '10',  'af' => '11',  'gb' => '16',  'fg' => '17',  'bc' => '18',  'bi' => '12',  'ci' => '8',  'cd' => '22',  'di' => '21',  'dg' => '24',  'gh' => '19',  'dh' => '16',  'de' => '20',  'eh' => '7',  'fe' => '26');$test = new Edge($a, $b);print_r($test->kruscal());?>

edge.php文件代码如下:

begin = $begin;    $this->end = $end;    $this->weight = $weight;  }  public function getBegin() {    return $this->begin;  }  public function getEnd() {    return $this->end;  }  public function getWeight() {    return $this->weight;  }}class Edge {  //边集数组实现图  private $vexs; //顶点集合  private $arc; //边集合  private $arcData; //要构建图的边信息  private $krus; //kruscal算法时存放森林信息  public function Edge($vexsData, $arcData) {    $this->vexs = $vexsData;    $this->arcData = $arcData;    $this->createArc();  }  //创建边  private function createArc() {    foreach ($this->arcData as $key => $value) {      $key = str_split($key);      $this->arc[] = new EdgeArc($key[0], $key[1], $value);    }  }  //对边数组按权值排序  public function sortArc() {    $this->quicklySort(0, count($this->arc) - 1, $this->arc);    return $this->arc;  }  //采用快排  private function quicklySort($begin, $end, &$item) {    if ($begin = $end)) return;    $key = $this->excuteSort($begin, $end, $item);    $this->quicklySort(0, $key - 1, $item);    $this->quicklySort($key + 1, $end, $item);  }  private function excuteSort($begin, $end, &$item) {    $key = $item[$begin];    $left = array();    <i>1本文来#源gaodai$ma#com搞$代*码*网</i><pre>搞代gaodaima码

$right = array(); for ($i = ($begin + 1); $i getWeight() getWeight()) { $left[] = $item[$i]; } else { $right[] = $item[$i]; } } $return = $this->unio($left, $right, $key); $k = 0; for ($i = $begin; $i krus = array(); $this->sortArc(); foreach ($this->vexs as $value) { $this->krus[$value] = “0”; } foreach ($this->arc as $key => $value) { $begin = $this->findRoot($value->getBegin()); $end = $this->findRoot($value->getEnd()); if ($begin != $end) { $this->krus[$begin] = $end; echo $value->getBegin() . “-” . $value->getEnd() . “:” . $value->getWeight() . “\n”; } } } //查找子树的尾结点 private function findRoot($node) { while ($this->krus[$node] != “0”) { $node = $this->krus[$node]; } return $node; }}?>

感兴趣的读者可以调试运行一下本文克鲁斯卡尔算法实例,相信会有新的收获。


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:PHP实现克鲁斯卡尔算法实例解析_php技巧
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址