made bfs more thread-safe and added a stop function for ending the bfs early