How to find shortest path using dijkstra algorithm?

9 次查看(过去 30 天)
Here, i have attached the code for shortest path using dijkstra algorithm and output image. In this, i give 21 nodes as input. In this code, i have following TWO doubts. 1.But in this output image, only first 10 nodes are shown other nodes are not shown. How solve this problem? 2. In this code, if i give start and finish node less than 10, it will work. If i give start and finish node greater than 10, it will not work. How to solve it?
nodes = [ 1 131 130; 2 281 135; 3 389 220; 4 132 290; 5 231 293; 6 392 395; 7 227 503; 8 137 504; 9 390 574; 10 145 672; 11 292 674; 12 131 1; 13 291 1; 14 1 135; 15 525 183; 16 1 292; 17 525 397; 18 1 504; 19 525 607; 20 1 672; 21 147 799];
segments = [(1:17); floor(1:0.5:9); ceil(2:0.5:10)]';
figure; plot(nodes(:,2), nodes(:,3),'k.');
hold on;
for s = 1:17
if (s <= 10) text(nodes(s,2),nodes(s,3),[' ' num2str(s)]); end
plot(nodes(segments(s,2:3)',2),nodes(segments(s,2:3)',3),'k');
end
[d, p] = dijkstra(nodes, segments, 3, 9)
for n = 2:length(p)
plot(nodes(p(n-1:n),2),nodes(p(n-1:n),3),'r-.','linewidth',2);
end
hold off;

回答(1 个)

Tridib
Tridib 2025-2-25
If you carefully look at the plot, all 21 nodes are being displayed, but only 10 have been labelled.
Also, “segments” could be more clearly defined to prevent any confusion. Additionally, edges only exist between the first 10 nodes. You might want to add edges among the remaining nodes as well.
Here is a simple code snippet that defines an adjacency matrix for a basic graph. It uses the Dijkstra function (https://www.mathworks.com/matlabcentral/fileexchange/36140-dijkstra-algorithm) to find the shortest path between nodes 1 and 4, highlighting them in red.
% You might consider converting your graph into an adjacency matrix format and
% then using it with the function.
A = [0 1 1 1 1;
1 0 1 1 0;
1 1 0 1 1;
1 1 1 0 1;
1 0 1 1 0];
G = graph(A);
source = 1;
destination = 4;
[cost, route] = dijkstra(A, source, destination);
figure;
h = plot(G);
highlight(h, route, 'EdgeColor', 'r', 'LineWidth', 2);
highlight(h, route, 'NodeColor', 'r');
Hope this helps!

类别

Help CenterFile Exchange 中查找有关 Dijkstra algorithm 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by