【问题标题】:Dijkstra's path pythonDijkstra 的路径 python
【发布时间】:2017-11-08 04:34:18
【问题描述】:

我正在使用 Dijkstra 模块来创建一些映射路径的函数。 我已经将所有路径添加到列表中,但正在努力打印函数的路径位置。

这是我正在使用的图表

例如:

>>>prev, dist = dijkstra(g, ‘A’) 
>>>print_path(prev, ‘A’, ‘D’) 
‘D-B-A’

另外,我怎样才能创建一个函数来建议输入的最短路径?
示例:

>>> suggest = shortest(g, “A”, “D”)
>>> suggest
{'C','B',’E'}

这是我的代码:

from dijkstra import *

nodes = {'A', 'B', 'C', 'D', 'E'}

edges = [('A', 'B', 3), ('B', 'A', 3), ('A', 'C', 5), ('C', 'A', 5), 
         ('A', 'E', 2), ('B', 'D', 2), ('D', 'C', 1), ('C', 'E', 2), 
         ('D', 'E', 4), ('E', 'D', 4)]

map1 = (nodes, edges)

src = 'A'
prev, dist = dijkstra(map1, src)
print('Dijkstra for sources = ', src, '\nprev: ', prev, '\nDistances: ', dist)


g = create_graph()
add_vertex(g, "A")
add_vertex(g, "B")
add_vertex(g, "C")
add_vertex(g, "D")
add_vertex(g, "E")

add_edge(g, 'A', 'B', 3)
add_edge(g, 'B', 'A', 3)
add_edge(g, 'A', 'C', 5)
add_edge(g, 'C', 'A', 5)
add_edge(g, 'A', 'E', 2)
add_edge(g, 'E', 'A', 2)
add_edge(g, 'B', 'D', 2)
add_edge(g, 'D', 'B', 2)
add_edge(g, 'D', 'C', 1)
add_edge(g, 'C', 'E', 2)
add_edge(g, 'E', 'C', 2)
add_edge(g, 'D', 'E', 4)
add_edge(g, 'E', 'D', 4)


def print_path(previous, source, dest):
   print('path from', source, 'to', dest, ':')

for node in map1[0]:
   print_path(prev, 'A', node)

【问题讨论】:

  • 欢迎来到 SO。请阅读此how-to-ask 并将图片发布到问题中。
  • 拜托,我需要有人帮忙

标签: python graph-theory dijkstra


【解决方案1】:

首先输入矩阵的度数 然后输入矩阵的数字,使其成为邻接矩阵 然后输入源和目标

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

def graph(mat, n, s, t):
    G = nx.Graph()
    for i in range(0, n):
        for j in range(0, n):
            if (i < j):
                if (mat[i][j] != 0):
                    e = mat[i][j]
                    G.add_edge(f"{i}", f"{j}", weight = e)

    nx.draw(G, with_labels = True)
    print("Path is\t", nx.dijkstra_path(G, source = s, target = t))
    plt.show()

n = int(input("enter degree of matrix:  "))
a = list(map(int, input("enter numbers:  ").split()))
mat = np.array(a).reshape(n, n)
print(mat)
s = str(input("enter source:  "))
t = str(input("enter target:  "))
graph(mat, n, s, t)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-06
    • 1970-01-01
    • 1970-01-01
    • 2014-08-07
    • 1970-01-01
    • 2018-11-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多