Skip to content
Advertisement

BFS algorithm in Python

JavaScript

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

or use a generator expression:

JavaScript

Lists don’t support subtraction.

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

JavaScript

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

Demo:

JavaScript
Advertisement