同步操作将从 编程语言算法集/Python 强制同步,此操作会覆盖自 Fork 仓库以来所做的任何修改,且无法恢复!!!
确定后同步将在后台操作,完成时将刷新页面,请耐心等待。
"""Program to check if a cycle is present in a given graph"""def check_cycle(graph: dict) -> bool:"""Returns True if graph is cyclic else False>>> check_cycle(graph={0:[], 1:[0, 3], 2:[0, 4], 3:[5], 4:[5], 5:[]})False>>> check_cycle(graph={0:[1, 2], 1:[2], 2:[0, 3], 3:[3]})True"""# Keep track of visited nodesvisited = set()# To detect a back edge, keep track of vertices currently in the recursion stackrec_stk = set()for node in graph:if node not in visited:if depth_first_search(graph, node, visited, rec_stk):return Truereturn Falsedef depth_first_search(graph: dict, vertex: int, visited: set, rec_stk: set) -> bool:"""Recur for all neighbours.If any neighbour is visited and in rec_stk then graph is cyclic.>>> graph = {0:[], 1:[0, 3], 2:[0, 4], 3:[5], 4:[5], 5:[]}>>> vertex, visited, rec_stk = 0, set(), set()>>> depth_first_search(graph, vertex, visited, rec_stk)False"""# Mark current node as visited and add to recursion stackvisited.add(vertex)rec_stk.add(vertex)for node in graph[vertex]:if node not in visited:if depth_first_search(graph, node, visited, rec_stk):return Trueelif node in rec_stk:return True# The node needs to be removed from recursion stack before function endsrec_stk.remove(vertex)return Falseif __name__ == "__main__":from doctest import testmodtestmod()
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。