Creating a program to find longest path
I'm fairly new to programming and I'm having a few problems. Basically I have to make a function that will find the lengths of all the paths through a network diagram. I've been working on this for hours but I can't seem to get anywhere. Using recursion I can navigate through every path but I'm just unsure as to how I should record the lengths of the paths.
Any help would be greatly appreciated. Thanks!
Edit: More info. The dependencies array is the dependencies for each path on the network. So path six is linked to paths 4 and 2, path 5 is lined to path 3, etc. The durations are the times that each path takes, so path 6 takes 10 hours, path 5 would takes 9 hours, etc.
The paths 1,2 and 3 with no dependencies expand from a start point and the paths 5 and 6 which are not depended on all converge to an end point. So I have to find the durations of all the pathways fr开发者_JAVA百科om the start to finish. The approach I've taken so far is go from the end point to start point and at this point my code can find all the pathways, I'm just having a lot of trouble figuring out how to record all durations separately. Thanks.
$dependencies = array("","","","1","3","4,2");
$durations = array("5","3","4","11","9","10");
function tracePath($path,$dependencies,$durations,$returnArray=array()) {
if($dependencies[$path] != "") {
$currentTaskDependencies = preg_split("/[\s]*[,][\s]*/", $dependencies[$path]);
for($i=0;$i<count($currentTaskDependencies);$i++) {
tracePath($currentTaskDependencies[$i]-1,$dependencies,$durations,$returnArray[$i]);
}
}
return $returnArray;
}
tracePath(6,$dependencies,$durations);
Why do you need to work out every conceivable path? Your question title says you're looking for the longest path, so surely this is simply the reverse of a shortest path algorithm, so Djikstra's Algorithm http://en.wikipedia.org/wiki/Dijkstra's_algorithm or Floyd Warshall http://en.wikipedia.org/wiki/Floyd%E2%80%93Warshall_algorithm (as alreday mentioned).
精彩评论