Write an algorithm to detect cycles in a network topology graph.
Implement detect_cycle(graph, directed), where graph is an adjacency-list dictionary and directed selects directed or undirected cycle rules. Return True if any cycle exists, otherwise return False. The graph may contain disconnected components, self-loops, and nodes with no outgoing edges.
def detect_cycle(graph, directed):