1. 程式人生 > >基於MATLAB的dijkstra演算法及其應用

基於MATLAB的dijkstra演算法及其應用

clc; clear; close all;
%% 載入設定資料
points = load('c:\\niu\\點的資料.txt');
lines = load('c:\\niu\\邊資料.txt');
A = ones(size(points, 1))*Inf;
for i = 1 : size(A, 1)
    A(i, i) = 0;
end
%% 繪圖
figure('NumberTitle', 'off', 'Name', '連線關係', 'Menu', 'None', ...
    'Color', 'w', 'units', 'normalized', 'position', [0 0 1 1]);
hold on; axis off;
plot(points(:, 2), points(:, 3), 'r.', 'MarkerSize', 20);
for i = 1 : size(lines, 1)
    temp = lines(i, :);
    pt1 = points(temp(1), 2 : end);
    pt2 = points(temp(2), 2 : end);
    len = norm([pt1(1)-pt2(1), pt1(2)-pt2(2)]);
    A(temp(1), temp(2)) = len;
    plot([pt1(1) pt2(1)], [pt1(2) pt2(2)], 'k-', 'LineWidth', 2);
end
% A就是連線矩陣,其中對角線為0,表示本身
% 有連線關係的就對應線的長度
% 沒有連線關係的就對應inf
%% 下面的是dijstra演算法,有兩種方式可以呼叫
s = 10; % 起點
e = 100; % 終點
[distance,path0] = dijkstra(A,s,e);
fprintf('\n Use Dijkstra the Min Distance is: %.5f \n', distance);
fprintf('\n Use Dijkstra the Min Distance path is: \n');
disp(path0);
A1 = A;
A1(isinf(A1)) = 0;
[d, p, pred] = graphshortestpath(sparse(A1), s, e);
fprintf('\n Use graphshortestpath the Min Distance is: %.5f \n', d);
fprintf('\n Use graphshortestpath the Min Distance path is: \n');
disp(p);