refactored dfs function