【问题标题】:Breadth-first search algorithm广度优先搜索算法
【发布时间】: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


【解决方案1】:

你的代码有很多问题-

    1234563 .
  1. 其次,在for循环中,你正在检查element == 0,这是错误的,你需要检查graphv[element] == 0,即元素是否已经被访问过。

  2. 第三,在for循环中,需要设置graphv[element] = count,表示你激活了element

  3. 您没有使用 - visited.put() 将任何内容放入队列中,您需要将要放入队列中的元素作为参数传递。

  4. 从队列中取回元素时,需要将其赋值回v,否则v永远不会改变,v表示当前正在迭代的元素。

    李>

示例代码-

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()
    visited.put(v)
    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 graphv[element] == 0:
                count = count + 1
                # mark w with count
                graphv[element] = count
                visited.put(element)
        v = visited.get()
    return count

if __name__ == '__main__':
    sys.exit(main())

演示(经过上述更改)-

{0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0}
Visiting 0
queue is not empty
queue is not empty
queue is not empty
queue is not empty
queue is not empty
queue is not empty
{0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6}

【讨论】:

  • 这就是答案。进一步的建议是避免使用Queue.Queue(用于多线程应用程序中的同步)并改用collections.deque
  • @Anand S Kumar 非常感谢!我总是对比较字典中的元素感到困惑,您对队列方法的解释非常有意义。我会记住这一点,以防将来出现问题!
【解决方案2】:

您可以使用提供搜索算法的图形库之一,例如 NetworkX:

from networkx import *
graphAL2 = {0 : [1,2,3],
        1 : [0,3,4],
        2 : [0,4,5],
        3 : [0,1,5],
        4 : [1,2],
        5 : [2,3] }

g = Graph()

# create graph
for node in graphAL2:
    g.add_node(node)
    for target_node in graphAL2[node]:
        g.add_edge(node, target_node)

print bfs_successors(g, 0)

这将获得每个节点的后继者,从中导出搜索顺序应该是小菜一碟。

输出:

{0: [1, 2, 3], 1: [4], 2: [5]}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-16
    相关资源
    最近更新 更多