improved impl for bfs & dfs