BFS algorithm in Python

拈花ヽ惹草 提交于 2019-12-13 23:41:14

问题


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

def bfs(graph, start, path=[]):
    queue = [start]
    while queue:
        vertex = queue.pop(0)
        if vertex not in path:
            path.append(vertex)
            queue.extend(graph[vertex] - path)
    return path

print bfs(graph, 0)

Guys! Can someone help me with this bfs code? I can't understand how to solve this queue line.


回答1:


To extend your queue with all nodes not yet seen on the path, use set operations:

queue.extend(set(graph[vertex]).difference(path))

or use a generator expression:

queue.extend(node for node in graph[vertex] if node not in path)

Lists don't support subtraction.

You don't really need to filter the nodes, however, your code would work with a simple:

queue.extend(graph[vertex])

as the if vertex not in path: test also guards against re-visiting nodes.

You should not use a list as default argument, see "Least Astonishment" and the Mutable Default Argument; you don't need a default argument here at all:

def bfs(graph, start):
    path = []

Demo:

>>> graph={ 0:[1,3,4], 1:[0,2,4], 2:[1,6], 3:[0,4,6], 4:[0,1,3,5], 5:[4], 6:[2,3] }
>>> def bfs(graph, start):
...     path = []
...     queue = [start]
...     while queue:
...         vertex = queue.pop(0)
...         if vertex not in path:
...             path.append(vertex)
...             queue.extend(graph[vertex])
...     return path
... 
>>> print bfs(graph, 0)
[0, 1, 3, 4, 2, 6, 5]



回答2:


queue.extend(graph[vertex] - path)

This line is giving TypeError: unsupported operand type(s) for -: 'list' and 'list', because you are not allowed to subtract two lists. You could convert them to a different collection that does support differences. For example:

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

def bfs(graph, start, path=[]):
    queue = [start]
    while queue:
        vertex = queue.pop(0)
        if vertex not in path:
            path.append(vertex)
            queue.extend(set(graph[vertex]) - set(path))
    return path

print bfs(graph, 0)

Result:

[0, 1, 3, 4, 2, 6, 5]

By the way, it may be good to modify the argument list so that you don't have a mutable list as a default:

def bfs(graph, start, path=None):
    if path == None: path = []



回答3:


Bug is that there is no list difference method. Either you can convert it to set and use set difference method or you can use list comprehension as

queue.extend(graph[vertex] - path)

can be replaced by

queue += [i for i in graph[vertex] if i not in path].



来源:https://stackoverflow.com/questions/23477921/bfs-algorithm-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!