Dijkstra的路径python

时间:2017-06-07 01:46:52

标签: python graph-theory dijkstra

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

这是我正在使用的图表

Path Graph

例如:

>>>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)

1 个答案:

答案 0 :(得分: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)