Quick actions

cmd+k|ctrl+k

Navigation

Languages

cycle

Snippet info

Language

Python

Visibility

public

Author

sriram

Created

2025-05-12T06:48:56.199931Z

Updated

2025-05-12T06:48:56.199931Z

def dfs(node,parent):
    visited.add(node)
    for neighbor in graph[node]:
        if neighbor not in visited :
            if dfs(neighbor, node):  
                return True
        elif neighbor in visited and neighbor!=parent:
            return True
        
    return False
    
graph = {
    'A': ['B', 'C', 'D'],
    'B': ['A', 'E'],
    'C': ['A', 'D', 'E'],
    'D': ['A', 'C'],
    'E': ['B', 'C']
}
visited=set()
for node in graph:
    if node not in visited:
        if dfs(node, None):  # If cycle is detected
            print("Cycle Detected")
            break
else:
    print("No Cycle Detected")
INFO