6-12 Shortest Path [2] (25 分)【单元最短路径 - 迪杰斯特拉】

这段代码实现的是Dijkstra算法,用于找到给定图中源点S到所有其他顶点的最短路径。它通过维护一个未访问顶点集合,并逐步更新最短距离,直到遍历完整个图。算法首先初始化所有顶点的距离为无穷大,源点S的距离为0,然后不断寻找当前未访问顶点中距离最小的一个,更新其相邻顶点的距离。
摘要由CSDN通过智能技术生成
void ShortestDist( MGraph Graph, int dist[], Vertex S ){
    int n=Graph->Nv;
    for(int i=0;i<n;i++){
        dist[i]=Graph->G[S][i];
    }
    int vis[MaxVertexNum]={0};
    vis[S]=1;
    dist[S]=0;
    int min,v;
    for(int i=0;i<n;i++){
        min=INFINITY;
        v=-1;
        for(int j=0;j<n;j++){
            if(vis[j]==0&&dist[j]<min){
                v=j;
                min=dist[j];
            }
        }
        if(v==-1)		//源点S与v点不连通,则跳到下一个点,否则调整未选择点集合中的路径长度
            continue;
        vis[v]=1;
        for(int j=0;j<n;j++){
            if(vis[j]==0&&((dist[v]+Graph->G[v][j])<dist[j])){
                dist[j]=dist[v]+Graph->G[v][j];
            }
        }
    }
    for(int i=0;i<n;i++){
        if(dist[i]==INFINITY)
            dist[i]=-1;
    }
}
迪杰斯特拉算法(Dijkstra's algorithm)是一种用于寻找带权图中单源最短路径的算法。其基本思想是从源点开始,不断地确定离源点距离最短的顶点,直到到达终点为止。 下面是迪杰斯特拉算法的 MATLAB 代码实现: ```matlab function [dist, path] = dijkstra(graph, start, dest) % DIJKSTRA Find the shortest path in a weighted graph using Dijkstra's algorithm % [DIST, PATH] = DIJKSTRA(GRAPH, START, DEST) finds the shortest path from % START to DEST in the weighted graph represented by the adjacency matrix GRAPH. % The output DIST is the length of the shortest path and PATH is a vector of % node indices representing the path. n = size(graph, 1); % number of nodes in the graph dist = inf(1, n); % initialize distance vector to infinity dist(start) = 0; % distance to start node is zero visited = false(1, n); % initialize visited vector to false prev = zeros(1, n); % initialize previous node vector to zero for i = 1:n-1 % find the node with the shortest distance that has not been visited [mindist, u] = min(dist .* ~visited); if isinf(mindist) break; % all remaining nodes are inaccessible end visited(u) = true; % mark the node as visited % update distances to neighboring nodes for v = find(graph(u, :)) alt = dist(u) + graph(u, v); if alt < dist(v) dist(v) = alt; prev(v) = u; end end end % construct path vector if isinf(dist(dest)) path = []; else path = dest; while path(1) ~= start path = [prev(path(1)), path]; end end end ``` 上述代码中,`graph` 是一个邻接矩阵,`start` 是起点的索引,`dest` 是终点的索引。函数返回两个输出参数,`dist` 是起点到终点的最短距离,`path` 是最短路径上经过的节点索引。如果起点与终点不连通,则 `dist` 为无穷大,`path` 为空。 相关问题: 1. 什么是带权图? 2. 迪杰斯特拉算法的时间复杂度是多少? 3. 迪杰斯特拉算法与贪心算法有什么联系?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值