LeetCode 207. Course Schedule

This question is actually asking how to check whether a graph has a cycle:

1. Put all nodes and it's next node into a hashmap. e.g 1 -> [2,3]

2. For each node, perform DFS, recursively check if there's a cycle. Create a state array, 0 = not assigned, 1 = checked, -1 = is checking

3. In each DFS, perform:

            i. if the node is check, then it would be a cycle.

            ii. if the node is checked, no need to continue.

            iii.  if the node is not a hashmap key, which means it's the end of the current branch, assign the state to 1, return true;

            iv. Assign the node to -1, currently checking.

            v. If the node is not assigned, DFS the next node, if any of the step is false, return false.

            vi. After check its children, and no false, then there's no cycle, return true.

 Code: 


            

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容