[10] | 1 | %GRAPHPATH Compute shortest paths in a graph
|
---|
| 2 | %
|
---|
| 3 | % [PATH,D] = GRAPHPATH(N,L,E)
|
---|
| 4 | %
|
---|
| 5 | % INPUT
|
---|
| 6 | % N Index of start node
|
---|
| 7 | % L Nx2 array with indices of all connected nodes in the graph
|
---|
| 8 | % E Vector with N corresponding distances
|
---|
| 9 | % Default: all distances equal to 1
|
---|
| 10 | %
|
---|
| 11 | % OUTPUT
|
---|
| 12 | % PATH Cell array with paths from node N to all other nodes
|
---|
| 13 | % D Cell array with edge length of paths in PATH
|
---|
| 14 | %
|
---|
| 15 | % DESCRIPTION
|
---|
| 16 | % The shortest paths are found from node N to all other nodes
|
---|
| 17 | % in the graph defined by {L,E}
|
---|
| 18 | %
|
---|
| 19 | % SEE ALSO
|
---|
| 20 | % DISTGRAPH, PLOTGRAPH, KMST
|
---|
| 21 |
|
---|
| 22 | % Copyright: R.P.W. Duin, r.p.w.duin@prtools.org
|
---|
| 23 | % Faculty EWI, Delft University of Technology
|
---|
| 24 | % P.O. Box 5031, 2600 GA Delft, The Netherlands
|
---|
| 25 |
|
---|
| 26 | function [nodepath,pathdist] = graphpath(nstart,L,e);
|
---|
| 27 |
|
---|
| 28 | L = [L; fliplr(L)];
|
---|
| 29 | n = size(L,1);
|
---|
| 30 | if nargin < 3
|
---|
| 31 | e = ones(n,1);
|
---|
| 32 | else
|
---|
| 33 | e = [e(:);e(:)];
|
---|
| 34 | end
|
---|
| 35 | k = max(L(:));
|
---|
| 36 |
|
---|
| 37 | nodedist = repmat(inf,1,k); % distance of node to source
|
---|
| 38 | nodeconn = cell(1,k); % connections per node
|
---|
| 39 | nodepath = cell(1,k); % path from source to each node
|
---|
| 40 | pathdist = cell(1,k); % distances along path
|
---|
| 41 | edgelen = cell(1,k);
|
---|
| 42 | for j=1:k
|
---|
| 43 | J = find(L(:,1)==j);
|
---|
| 44 | nodeconn{j} = L(J,2);
|
---|
| 45 | edgelen{j} = e(J);
|
---|
| 46 | end
|
---|
| 47 |
|
---|
| 48 | K = nstart; % active nodes
|
---|
| 49 | nodepath{nstart} = nstart;
|
---|
| 50 | nodedist(nstart) = 0;
|
---|
| 51 | pathdist{nstart} = 0;
|
---|
| 52 |
|
---|
| 53 | while ~isempty(K)
|
---|
| 54 | Knew = [];
|
---|
| 55 | for j=1:length(K)
|
---|
| 56 | C = nodeconn{K(j)}; % connecting nodes
|
---|
| 57 | for i=1:length(C)
|
---|
| 58 | ndist = nodedist(K(j)) + edgelen{K(j)}(i);
|
---|
| 59 | if ndist < nodedist(C(i))
|
---|
| 60 | nodedist(C(i)) = ndist;
|
---|
| 61 | nodepath{C(i)} = [nodepath{K(j)} C(i)];
|
---|
| 62 | pathdist{C(i)} = [pathdist{K(j)} edgelen{K(j)}(i)];
|
---|
| 63 | Knew = [Knew C(i)];
|
---|
| 64 | end
|
---|
| 65 | end
|
---|
| 66 | end
|
---|
| 67 | K = Knew;
|
---|
| 68 | end |
---|