refactoring + BFS (with bugs)