简体   繁体   English

Dijkstra算法python最佳路径

[英]Dijkstra algorithm python best path

i'm a begginer progammer and i really dont understand how to do a dijkstra algortihm.我是一个初学者程序员,我真的不明白如何做一个dijkstra algortihm。

I need a function that receive in arguments like我需要一个在 arguments 中接收的 function

def(connection, startPoint, endPoint):

and return the best path并返回最佳路径

Example:例子:

('a', 'b') is a connection
('a', 'c')  is a connection
('b', 'c')  is a connection

and return for example ('a', 'c') as the best path from 'a' to'c' (can be too 'a' 'b' 'c')并返回例如('a','c')作为从'a'到'c'的最佳路径(可以是'a''b''c')

I tried several codes but never came up with a possible solution.我尝试了几个代码,但从未想出一个可能的解决方案。 Someone help?有人帮忙吗?

There are a few things to consider when coming up with a solution.提出解决方案时需要考虑一些事项。 The first is how Dijkstra's algorithm itself works, and what data structures you're going to use in your solution.首先是 Dijkstra 算法本身的工作原理,以及您将在解决方案中使用的数据结构。 I would recommend reading up on it on Wikipedia before approaching the problem.我建议在解决问题之前先在 Wikipedia 上阅读它。 To start, we can first go through the instructions of the algorithm itself.首先,我们可以先通过算法本身的指令go。

Anyways, to be able to give a shortest path like the function signature in your post is effectively impossible, since the data of the graph itself needs to be given too.无论如何,要在您的帖子中提供像 function 签名这样的最短路径实际上是不可能的,因为图形本身的数据也需要提供。 To start, we can code up dijkstra's algorithm like so:首先,我们可以像这样编写 dijkstra 算法:

import heapq
from collections import deque
from math import inf
    

def dijkstra(graph, source):

    prev, unvisited = {}, []

    for vertex in graph:
        heapq.heappush(unvisited, (0 if vertex == source else inf, vertex))

    dist = dict(map(reversed, unvisited))

    while unvisited:
        _, nearest = heapq.heappop(unvisited)

        for neighbour, cost in graph[nearest].items():
            alt = dist[nearest] + cost
            if alt < dist[neighbour]:
                dist[neighbour] = alt
                prev[neighbour] = nearest

    return prev, dist

Now, given this algorithm, we know the order of visited nodes.现在,给定这个算法,我们知道访问节点的顺序。 Whatever is returned from here can be used to reconstruct the path from our source to our target, so we can create a function like the signature you've provided, but with a graph and target also added as a parameter.从这里返回的任何内容都可用于重建从源到目标的路径,因此我们可以像您提供的签名一样创建 function,但还添加了图形和目标作为参数。 That will look something like this:这看起来像这样:

def reconstruct_path(graph, dist, prev, source, target):

    path = deque()
    predecessor = target

    while predecessor is not None:
        path.appendleft(predecessor)
        predecessor = prev.get(predecessor)

    return path, cost

A graph in this case can simply be represented by a dictionary of strings (as nodes or vertices) mapped to another dictionary of strings (as nodes) to integers or floats (which in this case represent the cost of an edge).在这种情况下,一个图可以简单地由一个字符串字典(作为节点或顶点)映射到另一个字符串字典(作为节点)到整数或浮点数(在这种情况下表示边的成本)。

An example graph would be something like:示例图类似于:

test_graph = {
    "s": {"a": 1, "b": 5},
    "a": {"b": 2, "c": 2, "d": 1},
    "b": {"d": 2},
    "c": {"d": 3, "e": 1},
    "d": {"e": 2},
    "e": {},
}

So when we try to get the shortest path from a target vertex (in this example, we'll use "s"), with the following:因此,当我们尝试从目标顶点(在此示例中,我们将使用“s”)获取最短路径时,使用以下内容:

source = "s"
target = "b"

distances, predecessors = dijkstra(graph=test_graph, source=source, target=target)

print(reconstruct_path(graph=test_graph, dist=distances, prev=predecessors, target=target)

We get the following output:我们得到以下output:

path: ["s", "a", "b"]
cost: 3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM