python中使用BFS的无权单源最短路径
我是python新手。我尝试使用BFS获得未加权的单源最短路径python中使用BFS的无权单源最短路径,python,shortest-path,breadth-first-search,Python,Shortest Path,Breadth First Search,我是python新手。我尝试使用BFS获得未加权的单源最短路径 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
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中的列表、数组和队列也很陌生。如果你能帮助我,我将不胜感激。提前感谢这一行是您出错的原因:
queue2 = Queue
您将queue2
设置为等于Queue
类,而不是Queue
类的实例
将该行更改为:
queue2 = Queue()
首先,我在函数签名中添加了一个目标参数。假设您想找到从节点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()
两件事:首先,在Python中使用import*中的
被认为是不好的做法,因为这会使调试变得非常困难。第二,打开,所以发布回溯/错误消息很有帮助,这样人们就可以看到错误。错误是什么?当然。以下是错误:Traceback(最后一次调用):文件“C:/Users/svenp/PycharmProjects/or3/or4.py”,ussp(图2,1)文件“C:/Users/svenp/PycharmProjects/or3/or4.py”,第27行,ussp队列2中的第10行“C:\Users\svenp\AppData\Local\Programs\Python\Python36\lib\queue.py”,第184行,在put\u nowait return self.put(item,block=False)AttributeError:“list”对象没有属性“put”