用matlab求最短路线
2022-12-05 广告
N = 20; % 随机生成点的数量
x = rand(N,1); % 生成点的坐标
y = rand(N,1);
L = rand(N,N) > 0.9; % 随机生成连接关系(随机数大于门限值0.9为有连接)
D = round(squareform(pdist([x y]))*100)/100; % 计算各节点距离(保留两位小数)
DG = sparse(D.*L); % 用稀疏矩阵表示图
UG = tril(DG + DG'); % 转换为无向图
view(biograph(UG,[],'ShowArrows','off','ShowWeights','on'));% 显示图
% 计算任意(随机选择)两个节点间的最小路径
i = ceil(rand*N);
j = ceil(rand*N);
[dist,path,pred] = graphshortestpath(UG,i,j,'directed',false);
% 凸显出最短路径
h = view(biograph(UG,[],'ShowArrows','off','ShowWeights','on'));
set(h.Nodes(path),'Color',[1 0.4 0.4])
fowEdges = getedgesbynodeid(h,get(h.Nodes(path),'ID'));
revEdges = getedgesbynodeid(h,get(h.Nodes(fliplr(path)),'ID'));
edges = [fowEdges;revEdges];
set(edges,'LineColor',[1 0 0])
set(edges,'LineWidth',2)
运行结果如下图所示,因为数据是随机生成的,所以每次运算结果会有差异。