Python implementation of BFS algorithm