2 %> Algorithm 23.1: shortest paths. Implementation of algorithm 23.1 of \cite Bier15-book
4 %> @note Tested with \ref runShortestPath.m
7 %> @author Michel Bierlaire
8 %> @date Thu Apr 9 17:20:42 2015
12 %> Calculate the shortest paths from one origin to all nodes
13 %> @param adj adjacency matrix of the network. Each nonzero entry corresponds to an arc. The value of the entry is the ID of the arc.
14 %> @param cost the cost vector.
15 %> @param orig the origin node
16 %> @
return lambda the vector of labels
17 %> @
return pred the vector of the predecessors in the shortest path
19 addpath(
"../chap21") ;
22 lambda = realmax(nnodes,1) ;
24 % Length of the smallest simple path
25 lengthmin = (nnodes-1) * min(cost) ;
26 pred(1:nnodes,1) = -1 ;
27 listOfNodes = [orig] ;
29 while (!isempty(listOfNodes))
30 node = listOfNodes(1) ;
33 printf(
"%d ",listOfNodes) ;
34 printf(
"}\t%d\t",node) ;
36 if (lambda(i) == realmax)
39 printf(
"%d\t",lambda(i)) ;
42 % printf(
"%d\t",pred) ;
46 for arcij = adj(node,:)
48 nodej = arcs(arcij,2) ;
49 if (lambda(nodej) > lambda(node) + cost(arcij))
50 lambda(nodej) = lambda(node) + cost(arcij) ;
51 if (lambda(nodej) < 0 && lambda(nodej) < lengthmin)
52 error("A cycle of negative cost has been detected")
55 idx = find(listOfNodes == nodej) ;
57 listOfNodes(end+1) = nodej ;
66 if (lambda(i) == realmax) 69 printf("%d\t
",lambda(i)) ; 72 % printf("%d\t
",pred) ; function shortestPath(in adj, in cost, in orig)
Calculate the shortest paths from one origin to all nodes.
function prepareNetwork(in adj)
Identifies the upstream and downstream nodes of each arc.