Separated dfs & bfs logic