Fix bug where DFS doesn't terminate