refactoring of DFS