php - With graphp is there a quick way to enumerate ALL paths between two nodes? -
using graphp (the php library) there quick , easy way enumerate unique, loop-free paths between 2 nodes, or need create algorithm object accomplish this?
well, took stab @ writing quick , dirty recursive function rather try , implement graphp algorithm object... need testing , make sure spitting data in correct format, , inefficient appreciate feedback better ways want:
function recursive_find_paths($graph, $node, $dest, $path = array(), $visited ) { $paths = array(); array_push( $visited,$node->getid() ); // add node list of visited prevent loops if ( $node->getid() == $dest->getid() ) { return array($path); } // success! found path destination! foreach ($node->getverticesedgeto() $nextnode) { if ( in_array($nextnode->getid(),$visited) ) { continue; } // skip nodes if have 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 recursively calculated list of paths... }
it returning looking (i chose associative array later stick edge detail information regard each leg of path)
assuming simple square 4 vertices 1->2, 1->3, 2->4, 3->4 output:
array ( [0] => array ( [1->2] => 0.9 [2->4] => 0.9 ) [1] => array ( [1->3] => 0.9 [3->4] => 0.9 ) )
so keep playing code , see if can come better solutions. thanks.
Comments
Post a Comment