Using Graphp (the PHP library) is there a quick and easy way to enumerate all unique, loop-free paths between two nodes, or do i need to create an algorithm object to accomplish this?
1条回答 默认 最新
- dougan1465 2015-04-25 15:56关注
Well, i took a stab at writing a quick and dirty recursive function rather than try and implement a graphp algorithm object... I need to do some testing and make sure its spitting back the data in the correct format, and its completely inefficient but I would appreciate some feedback as to better ways to get to where I want:
function Recursive_Find_Paths($GRAPH, $NODE, $DEST, $PATH = array(), $VISITED ) { $PATHS = array(); array_push( $VISITED,$NODE->getId() ); // Add this node to the list of visited to prevent loops if ( $NODE->getId() == $DEST->getId() ) { return array($PATH); } // SUCCESS! We found a path to the destination! foreach ($NODE->getVerticesEdgeTo() as $NEXTNODE) { if ( in_array($NEXTNODE->getId(),$VISITED) ) { continue; } // SKIP nodes if we have already visited them! $NEXTPATH = $PATH; $A = $NODE->getId(); $B = $NEXTNODE->getId(); $NEXTPATH["{$A}->{$B}"] = 0.9; $MOREPATHS = Recursive_Find_Paths($GRAPH, $NEXTNODE, $DEST, $NEXTPATH, $VISITED); if ( count($MOREPATHS) ) { $PATHS = array_merge($PATHS,$MOREPATHS); } } return $PATHS; // Return the recursively calculated list of paths... }
It is returning what I am looking for (I chose an associative array so that I could later stick some Edge detail information with regard to each leg of the path)
Assuming a simple square with 4 Vertices 1->2, 1->3, 2->4, 3->4 I get this output:
Array ( [0] => Array ( [1->2] => 0.9 [2->4] => 0.9 ) [1] => Array ( [1->3] => 0.9 [3->4] => 0.9 ) )
So I will keep playing with the code and see if i can come up with any better solutions. Thanks.
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
- ¥15 java写代码遇到问题,求帮助
- ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
- ¥15 有了解d3和topogram.js库的吗?有偿请教
- ¥100 任意维数的K均值聚类
- ¥15 stamps做sbas-insar,时序沉降图怎么画
- ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
- ¥15 关于#Java#的问题,如何解决?
- ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
- ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计