Implements BFS to traverse the graph