source: distools/graphpath.m @ 70

Last change on this file since 70 was 10, checked in by bduin, 14 years ago
File size: 1.7 KB
Line 
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
26function [nodepath,pathdist] = graphpath(nstart,L,e);
27
28L = [L; fliplr(L)];
29n = size(L,1);
30if nargin < 3
31        e = ones(n,1);
32else
33        e = [e(:);e(:)];
34end
35k = max(L(:));
36
37nodedist = repmat(inf,1,k);  % distance of node to source
38nodeconn = cell(1,k);        % connections per node
39nodepath = cell(1,k);        % path from source to each node
40pathdist = cell(1,k);        % distances along path
41edgelen  = cell(1,k);
42for j=1:k
43        J = find(L(:,1)==j);
44        nodeconn{j} = L(J,2);
45        edgelen{j} = e(J);
46end
47
48K = nstart;                  % active nodes
49nodepath{nstart} = nstart;
50nodedist(nstart) = 0;
51pathdist{nstart} = 0;
52
53while ~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;
68end
Note: See TracBrowser for help on using the repository browser.