[英]Unweighted-Single-Source-Shortest-Path using BFS in python
我是python的新手。 我嘗試使用BFS獲得Unweighted-Single-Source-Shortest-Path。
from queue import *
def ussp(graph, s):
len_graph = len(graph)
prev = [[]*len_graph for i in range(len_graph)]
visited = [False for i in range(len_graph)]
queue2 = Queue
dist = [[float('inf')] for i in range(len_graph)]
queue2.put_nowait(graph[s], 0) # starting with s
visited[s] = True
dist[s] = 0
# modified BFS alg.
while queue2.empty() == False:
h = queue2.get_nowait()
for i in len(graph[h]):
if visited[graph[h][i]] == False:
visited[graph[h][i]] = True
dist[graph[h][i]] = dist[h] + 1
prev[graph[h][i]] = h
queue2.put_nowait(graph[h][i], 0)
print(dist)
graph2 = {1: [2, 3, 5], 2: [4, 6, 1], 3: [5, 1], 4: [6], 5: [2], 6: [1, 7], 7: [2]}
ussp(graph2, 1)
那就是我現在得到的。 我非常確定它應該可以工作,但是根本不起作用。 它甚至沒有被編譯。 我在python中使用列表,數組和隊列也很新。 如果您能幫助我,會很高興。 提前致謝
首先,我在函數簽名中添加了一個目標參數。 假設您想找到從節點1到節點7的最短路徑,下面的程序將起作用。 我還添加了一些python樣板,因為您說過您是python的新手。
import sys
from queue import Queue as Q
def ussp(graph, s, d):
len_graph = len(graph)
prev = [ -1 for i in range(len_graph)]
visited = [False for i in range(len_graph)]
q = Q()
dist = [sys.maxsize for i in range(len_graph)]
q.put(s, False)
visited[s-1] = True
dist[s-1] = 0
# modified BFS alg.
while q.empty() == False:
h = q.get_nowait()
for i in range(len(graph[h])):
if visited[graph[h][i]-1] == False:
visited[graph[h][i]-1] = True
dist[graph[h][i]-1] = dist[h-1] + 1
prev[graph[h][i]-1] = h
q.put_nowait(graph[h][i])
path = []
crawl = d # destination
path.append(crawl)
while (prev[crawl-1] != -1):
path.append(prev[crawl-1])
crawl = prev[crawl-1]
print(list(reversed(path)))
def main():
graph2 = {1: [2, 3, 5], 2: [4, 6, 1], 3: [5, 1], 4: [6], 5: [2], 6: [1, 7], 7: [2]}
ussp(graph2, 1, 7)
if __name__ == '__main__':
main()
此行是導致您出錯的原因:
queue2 = Queue
你設置queue2
等於Queue
,而不是一個實例類, Queue
類。
將該行更改為此:
queue2 = Queue()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.