简体   繁体   English

Python 2点之间的最短路径

[英]Python Shortest path between 2 points

I have found many algorithms and approaches that talk about finding the shortest path between 2 points , but i have this situation where the data is modeled as : 我发现许多算法和方法都在谈论寻找两点之间的最短路径,但是在这种情况下,数据建模为:

[(A,B),(C,D),(B,C),(D,E)...] # list of possible paths

If we suppose i need the path from A to E , the result should be: 如果我们假设我需要从A到E的路径,则结果应为:

(A,B)=>(B,C)=>(C,D)=>(D,E)

but i can't find a pythonic way to do this search. 但我找不到执行此搜索的Python方法。

The Pythonic way is to to use a module if one exists. Python的方式是使用一个模块(如果存在)。 As in this case, we know, networkx is there , we can write 在这种情况下,我们知道networkx在那,我们可以写

Implementation 实作

import networkx as nx
G = nx.Graph([('A','B'),('C','D'),('B','C'),('D','E')])
path = nx.shortest_path(G, 'A', 'E')

Output 输出量

zip(path, path[1:])
[('A', 'B'), ('B', 'C'), ('C', 'D'), ('D', 'E')]

If you think of your points as vertices in a graph, your pairs as edges in that graph, then you can assign to edge graph edge a weight equal to the distance between your points. 如果您将点视为图形中的顶点,将对视为该图形中的边,则可以为边图边缘分配一个权重,其权重等于点之间的距离。

Framed this way your problem is just the classic shortest path problem . 这样构造,您的问题就是经典的最短路径问题

You asked for a Pythonic way to write it. 您要求使用Python方式编写它。 The only advice I'd give is represent your graph as a dictionary, so that each key is a point, the returned values are a list of the other points directly reachable from that point. 我提供的唯一建议是将图形表示为字典,以便每个键都是一个点,返回值是从该点直接可到达的其他点的列表。 That will make traversing the graph faster. 这样可以更快地遍历图形。 graph[C] -> [B, D] for your example. graph[C] -> [B, D]为您的示例。

Here is a solution using A*: 这是使用A *的解决方案:

pip install pyformulas==0.2.8

import pyformulas as pf

transitions = [('A', 'B'), ('B', 'C'), ('C', 'A'), ('C', 'F'), ('D', 'F'), ('F', 'D'), ('F', 'B'), ('D', 'E'), ('E', 'C')]

initial_state = ('A',)

def expansion_fn(state):
    valid_transitions = [tn for tn in transitions if tn[0] == state[-1]]
    step_costs = [1 for t in valid_transitions]

    return valid_transitions, step_costs

def goal_fn(state):
    return state[-1] == 'E'

path = pf.discrete_search(initial_state, expansion_fn, goal_fn) # A*
print(path)

Output: 输出:

[('A',), ('A', 'B'), ('B', 'C'), ('C', 'F'), ('F', 'D'), ('D', 'E')]

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

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