1 | %DSPATH Single Shortest Path in a (Dissimilarity) Graph
|
---|
2 | %
|
---|
3 | % [D,P] = DSPATH (A,i,j)
|
---|
4 | %
|
---|
5 | % INPUT
|
---|
6 | % A NxN Weight / dissimilarity matrix or dataset
|
---|
7 | % i,j Vertices for which the shortest path should be found
|
---|
8 | %
|
---|
9 | % OUTPUT
|
---|
10 | % D Distance of the shortest path
|
---|
11 | % P List of edges of the shortest path
|
---|
12 | %
|
---|
13 | % DESCRIPTION
|
---|
14 | % Determines the shortest path between two vertices i and j. The Dijkstra's
|
---|
15 | % algorithm is used. Currently, it is not optimized fro speed in Matlab.
|
---|
16 | % A is a NxN matrix of weights (or a distance matrix) representing a graph
|
---|
17 | % G(V,E). V is a set of vertices, |V| = N, and E is a set of edges. If there
|
---|
18 | % is no edge between i and j then A(i,j) = INF. Use DSPATHS(A,'F') if all
|
---|
19 | % shortest paths should be computed.
|
---|
20 | %
|
---|
21 | % SEE ALSO
|
---|
22 | % DSPATHS
|
---|
23 | %
|
---|
24 | % LITERATURE
|
---|
25 | % Any book on graph algorithms or basic algorithms in computer science.
|
---|
26 |
|
---|
27 | % Elzbieta Pekalska, ela.pekalska@googlemail.com
|
---|
28 | % Faculty of EWI, Delft University of Technology, The Netherlands and
|
---|
29 | % School of Computer Science, University of Manchester
|
---|
30 |
|
---|
31 |
|
---|
32 | function [d, pt] = dspath(A,s,t)
|
---|
33 |
|
---|
34 | A = +A;
|
---|
35 | [n,m] = size(A);
|
---|
36 |
|
---|
37 | I = (1:n);
|
---|
38 | dmin(I) = 1e10;
|
---|
39 | final(I) = 0;
|
---|
40 | pred(I) = -1;
|
---|
41 |
|
---|
42 |
|
---|
43 | I(s) = [];
|
---|
44 | dmin(s) = 0;
|
---|
45 | final(s) = 1;
|
---|
46 | last = s;
|
---|
47 |
|
---|
48 | while ~final(t)
|
---|
49 | dminnew = dmin(last) + A(last,I);
|
---|
50 | Z = find(dminnew < dmin(I));
|
---|
51 | dmin(I(Z)) = dminnew(Z);
|
---|
52 | pred(I(Z)) = last;
|
---|
53 | [ss,last] = min(dmin(I));
|
---|
54 | last = I(last);
|
---|
55 | final(last) = 1;
|
---|
56 | I = setdiff(I,last);
|
---|
57 | end
|
---|
58 |
|
---|
59 | if nargout > 1,
|
---|
60 | if pred(t) ~= -1 % there is a path
|
---|
61 | k = t;
|
---|
62 | pt = t;
|
---|
63 | while k ~= s,
|
---|
64 | pt = [pred(k) pt];
|
---|
65 | k = pred(k);
|
---|
66 | end
|
---|
67 | else
|
---|
68 | pt = [];
|
---|
69 | end
|
---|
70 | end
|
---|
71 |
|
---|
72 | d = dmin(t);
|
---|
73 | return;
|
---|