switch out recursive dfs for stack based approach, to avoid possibly hitting the recursion limit