finish the BFS and DFS