dfs to detect cycle