Advertisement
stev4

Untitled

Jan 9th, 2020
421
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MatLab 1.71 KB | None | 0 0
  1. %##################################################################
  2. % Dijkstra's algorithm.
  3. %
  4. % INPUTS: adj - adjacency matrix (nxn), s - source node, target - target node
  5. % OUTPUTS: distance, d and path, P (from s to target)
  6. %
  7. % Note: if target==[], then dist and P include all distances and paths from s
  8. % Other routines used: adj2adjL.m
  9. % GB: last updated, Oct 5, 2012
  10. %##################################################################
  11.  
  12. function [dist,P]=dijkstra(adj,s,target)
  13.  
  14. n=length(adj);              % number of nodes
  15. adjL=adj2adjL(adj);         % list of neighbors
  16.  
  17. dist=inf(1,n);              % initialize distances
  18. dist(s)=0;
  19.  
  20. previous=[1:n; inf(1,n)]';  % {i: inf}, i=1:n, inf -> not assigned
  21. S=cell(1,n);                % initialize shortest path sequence
  22.  
  23.  
  24. Q=[1:n]; % all unvisited vertices, entire graph
  25.  
  26. while length(Q)>0 % while not empty
  27.  
  28.     % get min dist member among unvisited vertices
  29.     [mindist,min_ind]=min(dist(Q));
  30.     u=Q(min_ind);
  31.    
  32.     % termination condition - save "source-u" path
  33.     S{u}=[];
  34.     t=u;
  35.     while not(isempty(find(previous(:,1)==t)))  % t in previous.keys():
  36.         % insert u at the beginning of S
  37.         S{u}=[t S{u}];
  38.         t=previous(t,2);
  39.     end
  40.     if length(target)>0 & u==target
  41.         dist=dist(u); P=S{u};
  42.         return
  43.     end            
  44.    
  45.     % =====================================================
  46.     Q = setdiff(Q,u);         % remove u from Q
  47.    
  48.     for v=1:length(adjL{u})   % across all neighbors of u
  49.         v=adjL{u}(v);        
  50.         alt=dist(u)+adj(u,v);
  51.         if alt < dist(v)      % update the distance and path
  52.             dist(v)=alt;
  53.             previous(v,2)=u;
  54.         end
  55.     end
  56. end
  57.  
  58. P=S;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement