Implementing breadth-first-search algorithm