【发布时间】:2015-09-17 06:59:06
【问题描述】:
就像我之前遇到的一个问题一样,我正在尝试创建一个广度优先搜索算法,该算法采用图形并输出顶点访问顺序。它需要一个邻接矩阵(表示图形)作为其输入,这就是我目前所拥有的。
import sys
import Queue
# Input has to be adjacency matrix or list
graphAL2 = {0 : [1,2,3],
1 : [0,3,4],
2 : [0,4,5],
3 : [0,1,5],
4 : [1,2],
5 : [2,3] }
# NEED TO FIX:
# - Final graphAL2v print is only displaying key values as 1, not iterating
# through graph and visiting each vertex
def main():
count = 0
graphAL2v = {}
for key, value in graphAL2.items():
graphAL2v[key] = 0
print(graphAL2v)
for key in graphAL2v: # each vertex v in V
if graphAL2v[key] == 0: # is marked with 0
bfs(key, count, graphAL2, graphAL2v)
print(graphAL2v)
def bfs(v, count, graphal, graphv):
count = count + 1
print('Visiting', v)
# Mark v with count and initialize queue with v
graphv[v] = count
visited = Queue.Queue()
while not visited.empty(): #queue not empty:
print('queue is not empty')
for element in graphal[v]: # each vertex w in V adjacent to front vertex
if element == 0:
count = count + 1
# mark w with count
graphal[v] = count
visited.put()
visited.get()
if __name__ == '__main__':
sys.exit(main())
我遇到的问题是我的输出
{0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0}
('Visiting', 0)
('Visiting', 1)
('Visiting', 2)
('Visiting', 3)
('Visiting', 4)
('Visiting', 5)
{0: 1, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1}
当遍历“图表”时,应该将每个顶点的访问顺序显示为不同的数字时,列表中所有顶点的访问顺序显示为 1。我相信这个错误源于 bfs() 函数的 while 循环。关于尝试修复代码以便获得所需输出的任何建议?我也不太熟悉 Python 中的队列,因此不胜感激。
【问题讨论】:
-
程序不是递归的(还是我错过了?)
-
@amit 你是对的。我不确定为什么我说递归显然不是。整天忙这些事情,我的心一定要融化了
-
显示问题的最小图表是什么?
标签: python algorithm recursion queue breadth-first-search