2 %> Algorithm 23.2: Dijkstra. Implementation of algorithm 23.2 of \cite Bier15-book
4 %> @note Tested with \ref runDijkstra.m
7 %> @author Michel Bierlaire
8 %> @date Wed Thu Apr 9 17:22:28 2015
12 %> Calculate the shortest paths from one origin to all nodes
using Dijkstra
's algorithm 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 of each arc 15 %> @param orig the origin node 16 %> @param printlevel If different from 0, detailes about the iterations are printed. (Default: 0) 17 %> @return [lambda,pred] lambda is the vector of labels, pred is the vector of the predecessors in the shortest path 18 function [lambda,pred] = dijkstra(adj,cost,orig,printlevel=0) 19 addpath("../chap21") ; 20 arcs = prepareNetwork(adj) ; 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 [val, index] = min(lambda(listOfNodes)) ; 31 node = listOfNodes(index) ; 35 printf("%d ",listOfNodes) ; 36 printf("}\t%d\t",node) ; 38 if (lambda(i) == realmax) 41 printf("%d\t",lambda(i)) ; 47 listOfNodes(index) = [] ; 48 for arcij = adj(node,:) 50 nodej = arcs(arcij,2) ; 51 if (lambda(nodej) > lambda(node) + cost(arcij)) 52 lambda(nodej) = lambda(node) + cost(arcij) ; 53 if (lambda(nodej) < 0 && lambda(nodej) < lengthmin) 54 error("A cycle of negative cost has been detected") 57 idx = find(listOfNodes == nodej) ; 59 listOfNodes(end+1) = nodej ; 69 if (lambda(i) == realmax) 72 printf("%d\t",lambda(i)) ; function prepareNetwork(in adj)
Identifies the upstream and downstream nodes of each arc.