Fixed DFS bug by rewriting algorithm