lyqmath
http://blog.sina.com.cn/lyqmath
简介
dijkstra算法(迪杰斯特拉算法)是一种经典的优化算法。以其应用的广泛性与简便性,值得我们去研究。
Dijkstra算法是典型最短路算法,用于计算一个节点到其他所有节点的最短路径。主要特点是以起始点为中心向外层层扩展,直到扩展到终点为止。Dijkstra算法能得出最短路径的最优解,但由于它遍历计算的节点很多,所以效率低。(摘自网络,呵呵)
实例
这里给出一个基于MATLAB的dijkstra算法的实现函数,并给出MATLAB已有的dijkstra算法函数的调用情况。给出一个具体的例子。
路径分布图
function [distance,path]=dijkstra(A,s,e)
% [DISTANCE,PATH]=DIJKSTRA(A,S,E)
% returns the distance and path between the start node and the end node.
%
% A: adjcent matrix
% s: start node
% e: end node
% initialize
n=size(A,1);
D=A(s,:);
path=[];
visit=ones(1,n);
visit(s)=0;
parent=zeros(1,n);
% the shortest distance
for i=1:n-1
end
distance=D(e);
% the shortest distance path
if parent(e)==0
end
path=zeros(1,2*n);
t=e; path(1)=t; count=1;
while t~=s && t>0
end
if count>=2*n
end
path(1)=s;
path=path(1:count);
-------------------------------------------------------------
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)
end
%% 绘图
figure('NumberTitle', 'off', 'Name', '连接关系', 'Menu', 'None', ...
hold on; axis off;
plot(points(:, 2), points(:, 3), 'r.', 'MarkerSize', 20);
for i = 1 : size(lines, 1)
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);
for i = 1 : length(path0)
end
总结
dijkstra算法在优化、图像处理、网格处理等相关领域有非常广泛的应用,希望能借此机会了解其实质内容,并灵活应用其到所学领域中。