单源最短路径——dijistra算法

 题目链接:活动 - AcWing

算法步骤:
给定一个 n 个点 m 条边的有向图,图中可能存在重边和自环,所有边权均为正值。
请你求出 1 号点到 n 号点的最短距离,如果无法从 1 号点走到 n 号点,则输出 −1。
算法步骤
    1、维护一个数组N,两个集合P,Q,数组N用来储存起点到各个顶点的最短距离,集合P用来存储未遍历的点,集合Q存储已遍历的点。
    2、选择起点,将起点添加到Q集合中,并从P集合中删除。将与起点相邻的点的距离添加到数组中,到不相邻点的距离用无穷大表示。
    3、选择距离Q集合最近的一个点M(即与所有已遍历点相连的未遍历点中,边的权值最小的点)。将该点加入Q集合,并从P集合中删除。
    4、找到与M相邻的点C,计算数组N中存储的到达C点的距离是否小于起点经过M到达C点的距离,若是,则更新N,否则继续寻找下一个与M相邻的点,重复步骤4直到遍历完M的所有邻点。
    5、重复步骤3,4直至遍历集合P为空。



import java.util.*;

public class Dijkstra {
    public static int n, m;
    public static Scanner sc = new Scanner(System.in);
    public static final int N = 510;
    public static int[] dis=new int[N];//存储1号点到每个点的最短距离
    public static boolean[] st=new boolean[N];//每个点的最短路是否已经确定
    public static int[][] map=new int[N][N];//存储每条边

    public static int dijkstra(){
        Arrays.fill(dis,0x3f3f);//初始化距离为正无穷
        dis[1]=0;//初始化第一个点到自身的距离为0
        for (int i = 0; i < n; i++) {//n个点 都迭代一次
            int tmp=-1;//存储当前要访问的点
            //找出距离最近的点的下标
            for (int j = 1; j <=n ; j++) {//从1号点开始
                if(!st[j]&&(tmp==-1||dis[tmp]>dis[j])) tmp=j;
            }
            st[tmp]=true;//当前点已经使用过
            for (int j = 1; j <=n ; j++) {//依次更新距离更近的点
                dis[j]=Math.min(dis[j],dis[tmp]+map[tmp][j]);
                //初始化0x3f3f就够了,如果是Integer.MAX_VALUE再加上一个数就是变成负数,变成最小的那一个
            }
        }
        if(dis[n]==0x3f3f) return -1;
        return dis[n];
    }
    public static void main(String[] args) {
        n = sc.nextInt();//n个点
        m = sc.nextInt();//m条边
        for (int i = 0; i <=n; i++) {
            Arrays.fill(map[i],0x3f3f);
        }
        while (m-->0){
            int i=sc.nextInt(),j=sc.nextInt(),weight=sc.nextInt();
            map[i][j]=Math.min(weight,map[i][j]);
        }
        int res = dijkstra();
        System.out.println(res);
    }
}


       不难观察到,Dijkstra算法的特点主要是从起点开始,“由近及远,层层扩展”,越靠前处理的点离起点越近,最后一个处理的点一定离起点最远。
  所以,依据算法每找到一个顶点后,该顶点对应的值就是起点到该点的最短路径长度,且在这之后不会被更改。
  而最后一次迭代得到的所有的值,就是由起点(亦称源点)A到各点的最短路径长度。
  故Dijkstra算法解决的是有向图中的单源最短路问题。

 

离字典,将起始节距离设为0,其他节距离设为无穷大 distances = {node: sys.maxsize for node in graph} distances[start] = 0 # 初始化已访问节的集合和未访以下是使用问节D的集ijkstra合 visited = set() unvisited算法求解最短路径的Python = set(graph) while unvisited: # 代码示例: ```python class D选择当前ijkstra距: def __init__(self, graph离最小的节 , start, current goal): self.graph = graph # 邻接表_node = min(unvisited, key=lambda self node: distances[node]) # 更新.start = start当前节的 # 起邻居节 self.goal =的距离 goal # 终 for neighbor in graph self.open[current_node]: _list = {} if neighbor in # open 表 self.closed_list unvisited: new_distance = distances[current_node] + = {} graph[current_node][neighbor # closed 表 self.open_list[start] if new_distance] = < distances[neighbor]: 0.0 # 将 distances[neighbor] = new_distance # 将当前起点放入 open_list self.parent = {节标记start:为已访 None} 问,并从未访问集合移除 visited.add # 存储的父子关系。键为(current_node) 子节, unvisited值为父.remove(current_node) return节。方便做最 distances def print后_path(dist路径的ances,回 start溯 self.min, end): _dis = None # 根 # 最短路径的长度 def shortest_path据距离字典和终(self): while True: ,逆向 if self打印路径.open_list is path = [end None: ] print('搜索 current_node =失败 end while current_node !=, 结束!') break distance start: , min_node = for neighbor in graph min(zip[current_node]: if(self.open_list distances[current.values(), self_node] ==.open_list.keys distances[neighbor())) #] + graph 取出距[neighbor][current_node]: 离最小的节 self path.open_list.pop.append(min_node)(neighbor) current_node = neighbor break path.reverse() # 将其从 open_list 去除 self print.closed("_list[minShortest_node] = path from", distance # 将节加入 closed start, "to", end,_list ":", "->".join(path)) # 示例 if min_node == self.goal: # 如果节为图的邻接矩阵终 self.min_dis = distance 表示 graph shortest = { _path = [ 'Aself.goal]': {'B': # 5, 'C 记录从': 终1}, 回溯的路径 'B
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值