Improve DFS algorithm