图论——Dijkstra算法matlab代码

Dijkstra算法步骤

(1)构造邻接矩阵

(2)定义起始点

(3)运行代码

Matlab 复制代码
M=[  0     5     9   Inf   Inf   Inf   Inf
   Inf     0   Inf   Inf    12   Inf   Inf
   Inf     3     0    15   Inf    23   Inf
   Inf     6   Inf     0   Inf     8     7
   Inf    12   Inf     5     0   Inf    14
   Inf   Inf   Inf   Inf   Inf     0    10
   Inf   Inf   Inf   Inf   Inf   Inf     0];
first=2;
last=4;
[m,n]=size(M);
L=zeros(1,m);
symbol=zeros(1,m);
direction=zeros(1,m);
for i=1:m
    if(i~=first)
        L(i)=inf;
    end
    direction(i)=first;
end
judge=1;
while judge
for i=1:m
    if(symbol(i)==0)
        min=L(i);
        temporary=i;
        break
    end
end
for i=1:m
    if(symbol(i)==0)
        if(L(i)<min)
            min=L(i);
            temporary=i;
        end
    end
end
k=temporary;
for j=1:m
    if(symbol(1,j)==0)
        if(M(k,j)==inf)
            continue;
        else
            if(L(k)+M(k,j)<L(j))
                L(j)=L(k)+M(k,j);
                direction(j)=k;
            end
        end
    end
end
symbol(k)=1;
num=0;
for i=1:m
    if(symbol(i)==1)
        num=num+1;
    end
end
if(num==m)
    judge=0;
end
end
p=last;
arrow=zeros(1,m);
arrow(1)=last;
i=2;
while p~=first
    arrow(1,i)=direction(p);
    i=i+1;
    p=direction(p);
end
distance=L(last);
相关推荐
薛定谔的算法5 分钟前
《盗梦空间》与JavaScript中的递归
算法
kaiaaaa28 分钟前
算法训练第十一天
数据结构·算法
?!71430 分钟前
算法打卡第18天
c++·算法
springfe010143 分钟前
构建大顶堆
前端·算法
凌辰揽月1 小时前
Web后端基础(基础知识)
java·开发语言·前端·数据库·学习·算法
lifallen1 小时前
深入浅出 Arrays.sort(DualPivotQuicksort):如何结合快排、归并、堆排序和插入排序
java·开发语言·数据结构·算法·排序算法
jingfeng5141 小时前
数据结构排序
数据结构·算法·排序算法
能工智人小辰2 小时前
Codeforces Round 509 (Div. 2) C. Coffee Break
c语言·c++·算法
kingmax542120082 小时前
CCF GESP202503 Grade4-B4263 [GESP202503 四级] 荒地开垦
数据结构·算法
岁忧2 小时前
LeetCode 高频 SQL 50 题(基础版)之 【高级字符串函数 / 正则表达式 / 子句】· 上
sql·算法·leetcode