forked from shihchengyen/Hippocampus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdijkstra.m
executable file
·72 lines (65 loc) · 1.23 KB
/
dijkstra.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
%---------------------------------------------------
% Dijkstra Algorithm
% author : Dimas Aryo
% email : [email protected]
%
% usage
% [cost rute] = dijkstra(Graph, source, destination)
%
% example
% G = [0 3 9 0 0 0 0;
% 0 0 0 7 1 0 0;
% 0 2 0 7 0 0 0;
% 0 0 0 0 0 2 8;
% 0 0 4 5 0 9 0;
% 0 0 0 0 0 0 4;
% 0 0 0 0 0 0 0;
% ];
% [e L] = dijkstra(G,1,7)
%---------------------------------------------------
function [e L] = dijkstra(A,s,d)
if s==d
e=0;
L=[s];
else
A = setupgraph(A,inf,1);
if d==1
d=s;
end
A=exchangenode(A,1,s);
lengthA=size(A,1);
W=zeros(lengthA);
for i=2 : lengthA
W(1,i)=i;
W(2,i)=A(1,i);
end
for i=1 : lengthA
D(i,1)=A(1,i);
D(i,2)=i;
end
D2=D(2:length(D),:);
L=2;
while L<=(size(W,1)-1)
L=L+1;
D2=sortrows(D2,1);
k=D2(1,2);
W(L,1)=k;
D2(1,:)=[];
for i=1 : size(D2,1)
if D(D2(i,2),1)>(D(k,1)+A(k,D2(i,2)))
D(D2(i,2),1) = D(k,1)+A(k,D2(i,2));
D2(i,1) = D(D2(i,2),1);
end
end
for i=2 : length(A)
W(L,i)=D(i,1);
end
end
if d==s
L=[1];
else
L=[d];
end
e=W(size(W,1),d);
L = listdijkstra(L,W,s,d);
end