Moved code from dfs function to bfs function