JavaScript
x
13
13
1
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] }
2
3
def bfs(graph, start, path=[]):
4
queue = [start]
5
while queue:
6
vertex = queue.pop(0)
7
if vertex not in path:
8
path.append(vertex)
9
queue.extend(graph[vertex] - path)
10
return path
11
12
print bfs(graph, 0)
13
Guys! Can someone help me with this bfs code? I can’t understand how to solve this queue line.
Advertisement
Answer
To extend your queue with all nodes not yet seen on the path, use set operations:
JavaScript
1
2
1
queue.extend(set(graph[vertex]).difference(path))
2
or use a generator expression:
JavaScript
1
2
1
queue.extend(node for node in graph[vertex] if node not in path)
2
Lists don’t support subtraction.
You don’t really need to filter the nodes, however, your code would work with a simple:
JavaScript
1
2
1
queue.extend(graph[vertex])
2
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:
JavaScript
1
3
1
def bfs(graph, start):
2
path = []
3
Demo:
JavaScript
1
14
14
1
>>> 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] }
2
>>> def bfs(graph, start):
3
path = []
4
queue = [start]
5
while queue:
6
vertex = queue.pop(0)
7
if vertex not in path:
8
path.append(vertex)
9
queue.extend(graph[vertex])
10
return path
11
12
>>> print bfs(graph, 0)
13
[0, 1, 3, 4, 2, 6, 5]
14