迪克斯特拉';s路径python
我正在使用Dijkstra模块创建一些映射路径的函数。 我已经将所有路径添加到列表中,但是我正在努力打印函数的路径位置 这是我正在使用的图表 例如:迪克斯特拉';s路径python,python,graph-theory,dijkstra,Python,Graph Theory,Dijkstra,我正在使用Dijkstra模块创建一些映射路径的函数。 我已经将所有路径添加到列表中,但是我正在努力打印函数的路径位置 这是我正在使用的图表 例如: >>>prev, dist = dijkstra(g, ‘A’) >>>print_path(prev, ‘A’, ‘D’) ‘D-B-A’ 此外,如何创建一个函数来建议输入的最短路径? 例如: 这是我的密码: from dijkstra import * nodes = {'A', 'B', 'C',
>>>prev, dist = dijkstra(g, ‘A’)
>>>print_path(prev, ‘A’, ‘D’)
‘D-B-A’
此外,如何创建一个函数来建议输入的最短路径?例如: 这是我的密码:
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)
矩阵的初入度 然后输入矩阵的编号,使其成为邻接矩阵 然后输入源和目标
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)
将numpy导入为np
将networkx导入为nx
将matplotlib.pyplot作为plt导入
def图表(mat、n、s、t):
G=nx.Graph()
对于范围(0,n)内的i:
对于范围(0,n)内的j:
如果(i
欢迎来到SO。请阅读这篇文章并将图片贴到问题中。请,我需要有人帮助
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)