Implements the breadth first search.