Dijkstra迪杰斯特拉算法Python版本

11 篇文章 0 订阅
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time : 2022/1/31 14:14
# @Author : Jin Echo
# @File : Dijkstra.py

import heapq
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
import random


def dijkstra(adj, s):
    """

    :param adj: n*n的邻接矩阵
    :param s: 起点下标
    :return:
    """
    n = adj.shape[0]  # 顶点数
    pqueue = []
    heapq.heappush(pqueue, (0, s))  # <距离 起点>二元组
    visited = set()
    pre = np.arange(n)
    # 初始化
    distance = np.ones((n,)) * np.inf
    distance[s] = 0

    cnt = 0
    while len(visited) != n and len(pqueue):
        cnt += 1
        min_dis, min_node = heapq.heappop(pqueue)
        if min_node in visited:
            continue
        else:
            visited.add(min_node)
        neighbors = np.where((adj[min_node, :] < 1) & (adj[min_node, :] > 0))[0]  # 提取当前点的邻接点
        for neighbor in neighbors:
            if neighbor not in visited:
                if min_dis + adj[min_node][neighbor] < distance[neighbor]:
                    distance[neighbor] = min_dis + adj[min_node][neighbor]
                    heapq.heappush(pqueue, (distance[neighbor], neighbor))
                    pre[neighbor] = min_node
                    
    print(cnt)
    return pre, distance


def get_sequence(pre, node):
    """
    返回起点到指定节点的最短路径
    :param pre:
    :param node:
    """
    res = [node]
    while pre[node] != node:
        node = pre[node]
        res.append(node)
    res.reverse()
    return res


if __name__ == '__main__':
    np.random.seed(1)
    random.seed(1)
    n, m = 20, 4
    G = nx.barabasi_albert_graph(n, m)  # 生成图结构
    plt.figure(1)
    nx.draw(G, with_labels=True, font_weight='bold')

    edges_idx = np.array(G.edges)
    # print(edges_idx)
    num_edges = (n - m) * m  # 图中的边数,也等于edges_idx.shape[0]
    assert num_edges == edges_idx.shape[0]

    # 赋值边权
    adj = np.ones([n] * 2) * np.inf
    # adj[range(n), range(n)] = 0  # 主对角线为0
    adj[edges_idx[:, 0], edges_idx[:, 1]] = np.random.rand(num_edges)
    adj[edges_idx[:, 1], edges_idx[:, 0]] = adj[edges_idx[:, 0], edges_idx[:, 1]]

    s = 0
    pre, distance = dijkstra(adj, s)
    print(pre)
    print(distance)
    print(get_sequence(pre, n - 1))
    plt.show()
迪杰斯特拉算法Dijkstra's algorithm)是一种用于求解单源最短路径问题的算法。它可以找到从一个顶点到其他所有顶点的最短路径。 以下是迪杰斯特拉算法的基本步骤: 1. 创建一个空的距离字典,用于存储每个顶点到起始顶点的距离。将起始顶点的距离设置为0,其他顶点的距离设置为无穷大。 2. 创建一个空的已访问集合,用于存储已经找到最短路径的顶点。 3. 重复以下步骤,直到所有顶点都被访问: a. 从未访问的顶点中选择距离起始顶点最近的顶点,并将其添加到已访问集合中。 b. 更新与该顶点相邻的顶点的距离。如果通过当前顶点到达相邻顶点的路径比之前计算的路径更短,则更新距离字典中的值。 4. 最终,距离字典中存储了从起始顶点到每个顶点的最短路径。 以下是一个使用Python实现迪杰斯特拉算法的示例代码: ```python import sys def dijkstra(graph, start): # 初始化距离字典 distances = {vertex: sys.maxsize for vertex in graph} distances[start] = 0 # 初始化已访问集合 visited = set() while len(visited) < len(graph): # 选择距离最小的顶点 min_distance = sys.maxsize min_vertex = None for vertex in graph: if vertex not in visited and distances[vertex] < min_distance: min_distance = distances[vertex] min_vertex = vertex # 将选中的顶点添加到已访问集合中 visited.add(min_vertex) # 更新与选中顶点相邻的顶点的距离 for neighbor, weight in graph[min_vertex].items(): new_distance = distances[min_vertex] + weight if new_distance < distances[neighbor]: distances[neighbor] = new_distance return distances # 示例图的邻接表表示 graph = { 'A': {'B': 5, 'C': 3}, 'B': {'A': 5, 'C': 1, 'D': 3}, 'C': {'A': 3, 'B': 1, 'D': 2, 'E': 6}, 'D': {'B': 3, 'C': 2, 'E': 4, 'F': 2}, 'E': {'C': 6, 'D': 4, 'F': 6}, 'F': {'D': 2, 'E': 6} } start_vertex = 'A' distances = dijkstra(graph, start_vertex) for vertex, distance in distances.items(): print(f"从顶点 {start_vertex} 到顶点 {vertex} 的最短距离为 {distance}") ``` 这段代码实现了迪杰斯特拉算法,通过邻接表表示图,并计算从起始顶点到其他顶点的最短距离。你可以根据自己的需求修改图的表示和起始顶点。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值