Working version with bfs