[英]How to do shortest path algorithm for unweighted graph?
我試圖找到從一個頂點到另一個相連的,未加權圖的最短路徑。
在此問題中,從頂點到其相鄰頂點的距離將等於1。即,如果考慮具有邊(a,b),(a,c)的圖,則從a到b和c的距離將為為1,從b到c的距離為2。此外,維護鄰接表以存儲每個頂點的所有相鄰頂點。
那么,是否有任何算法可以找到給定問題的所有最短路徑?
您可以使用dijkstra的算法來查找距離。
這是使用networkx
的一種方法
In [28]: import networkx as nx
創建一個節點為a, b, c
的grpah a, b, c
其中鏈接為a, b
和“ a,c”
In [29]: g = nx.Graph()
In [30]: g.add_edge('a', 'b')
In [31]: g.add_edge('a', 'c')
然后使用nx.dijkstra_path_length()
找到b and c
之間的距離
In [32]: nx.dijkstra_path_length(g, 'b', 'c')
Out[32]: 2
另外,您可以使用dijkstra_path()
找到路徑軌跡
In [33]: nx.dijkstra_path(g, 'b', 'c')
Out[33]: ['b', 'a', 'c']
您還可以將shortest_path()
用於b and c
之間的路徑
In [34]: nx.shortest_path(g, source='b',target='c')
Out[34]: ['b', 'a', 'c']
您可以找到具有功能的所有路徑,然后選擇最小長度的路徑。
但請注意,此問題更多地取決於您的搜索算法,例如BFS算法:
您可以使用以下函數返回路徑生成器:
def all_paths(graph, start, goal):
queue = [(start, [start])]
while queue:
(v, path) = queue.pop(0)
for next in graph[v] - set(path):
if next == goal:
yield path + [next]
else:
queue.append((next, path + [next]))
並以len
為鍵找到具有min
函數的最小路徑:
min_path = min(all_paths(graph, start, goal),key=len)
您可以從那時開始使用BFS: http : //en.wikipedia.org/wiki/Breadth-first_search
您也可以使用Floyd–Warshall算法,如果時間不成問題,並且想要簡化操作,則運行O(n ^ 3): http : //en.wikipedia.org/wiki/Floyd%E2%80%93Warshall_algorithm
Dijkstra算法解決了“在圖形中找到兩個頂點(或節點)之間的路徑,以使其組成邊的權重之和最小化的問題”。
http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm
因此,我認為您可以使用Dijkstra解決此問題,其中對於兩個頂點之間的每條路徑,從頂點到其相鄰頂點的距離都相等。
無論如何,您都可以使用BFS http://en.wikipedia.org/wiki/Breadth-first_search
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.