# Adapting Dijkstra to list all shortest paths [duplicate]

I found a code in the internet for Dijkstra's shortest path algorithm in PHP. The problem is it only shows one possible path. If there are several paths having the same distance, it only outputs one of them.

How can I modify this algorithm to produce all shortest paths?

 

//set the distance array $_distArr = array();$_distArr = 7; $_distArr = 9;$_distArr = 14; $_distArr = 7;$_distArr = 10; $_distArr = 15;$_distArr = 9; $_distArr = 10;$_distArr = 11; $_distArr = 2;$_distArr = 15; $_distArr = 11;$_distArr = 6; $_distArr = 6;$_distArr = 9; $_distArr = 14;$_distArr = 2; $_distArr = 9;  //the start and the end$a = 1; $b = 6; //initialize the array for storing$S = array();//the nearest path with its parent and weight $Q = array();//the left nodes without the nearest path foreach(array_keys($_distArr) as $val)$Q[$val] = 99999;$Q[$a] = 0; //start calculating while(!empty($Q)){ $min = array_search(min($Q), $Q);//the most min weight if($min == $b) break; foreach($_distArr[$min] as$key=>$val) if(!empty($Q[$key]) &&$Q[$min] +$val < $Q[$key]) { $Q[$key] = $Q[$min] + $val;$S[$key] = array($min, $Q[$key]); } unset($Q[$min]); } //list the path $path = array();$pos = $b; while($pos != $a){$path[] = $pos;$pos = $S[$pos]; } $path[] =$a; $path = array_reverse($path); //print result echo "From $a to$b"; echo "The length is ".$S[$b]; echo "Path is ".implode('->', \$path); 

?> 

• There's no search algorithm in the code you showed, only what seems to be the steps to print the path once it's been calculated. – giusti Jan 15 '17 at 10:04
• Programming questions are off-topic here. – Yuval Filmus Jan 15 '17 at 11:08
• Heads up: There can be an exponential number of shortest paths between two vertices. – orezvani Jan 15 '17 at 11:11
• For example, if all the distances are zero, so each path is a shortest path. That even gives you an infinite number of shortest paths. – gnasher729 Jan 15 '17 at 11:47
• Welcome to Computer Science! Please get rid of the source code and replace it with ideas, pseudo code and arguments of correctness. See here and here for related meta discussions. – Raphael Jan 15 '17 at 12:00