shortest path algorithm based on a recursive function

4 visualizaciones (últimos 30 días)
feynman feynman
feynman feynman el 11 de Feb. de 2020
Comentada: Rena Berman el 14 de Mayo de 2020
The following code is correct 90% of the time. Anybody can find the bug?
function dis=wrong(node1,nodes,node2)
% distance node 1->node 2 thru intermediate nodes (\1, 2)
global W% weight matrix
if isempty(nodes)% 1->2 directly when nodes empty
dis=W(node1,node2);return;
end
% d(1,nodes,2)=min{W(1,i)+wrong(i,nodesSub,2),i}
for ii=1:length(nodes)
i=nodes(ii);
nodesSub=nodes;nodesSub(ii)=[];% remove i from nodesSub
disTemp(ii)=wrong(i,nodesSub,node2);
disTemp(ii)=W(node1,i)+disTemp(ii);% 1->i->2
end
disTemp(ii+1)=W(node1,node2);% 1->2 directly
% optimum route
[dis,im]=min(disTemp);
  2 comentarios
Stephen23
Stephen23 el 13 de Feb. de 2020
Original question copied here from Google Cache:
"shortest path algorithm based on a recursive function"
The following code is correct 90% of the time. Anybody can find the bug?
function dis=wrong(node1,nodes,node2)
% distance node 1->node 2 thru intermediate nodes (\1, 2)
global W% weight matrix
if isempty(nodes)% 1->2 directly when nodes empty
dis=W(node1,node2);return;
end
% d(1,nodes,2)=min{W(1,i)+wrong(i,nodesSub,2),i}
for ii=1:length(nodes)
i=nodes(ii);
nodesSub=nodes;nodesSub(ii)=[];% remove i from nodesSub
disTemp(ii)=wrong(i,nodesSub,node2);
disTemp(ii)=W(node1,i)+disTemp(ii);% 1->i->2
end
disTemp(ii+1)=W(node1,node2);% 1->2 directly
% optimum route
[dis,im]=min(disTemp);
Rena Berman
Rena Berman el 14 de Mayo de 2020
(Answers Dev) Restored edit

Iniciar sesión para comentar.

Respuestas (1)

Steven Lord
Steven Lord el 11 de Feb. de 2020
If you have a (small, simple) test case where the answer your code gives differs from the answer you expected it to give, have you tried debugging your code on that test case using the debugging tools included in MATLAB? You can step through your code line by line and compare what the results at each step are to what the results should be.
  3 comentarios
Steven Lord
Steven Lord el 11 de Feb. de 2020
You asked "Anybody can find the bug?" If you've tested it thoroughly, why do you think there is a bug?
Or did you mean "Can anybody find a bug in this code?" asking for the readers of MATLAB Answers to do some manual testing on your code to determine if there's a bug in your code not where a bug is in your code?
feynman feynman
feynman feynman el 13 de Feb. de 2020
close question please

Iniciar sesión para comentar.

Etiquetas

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by