Problem 508241 · medium · Phase 05 Advanced Algorithms & Graphs

Does the Network Contain a Loop?

graphs · DFS · cycle detection

A simple undirected graph (no self-loops, no repeated edges) has n nodes 0 .. n-1 and edge list edges (edges[i] = [u, v]). Return True if the graph contains at least one cycle, False otherwise. The graph may be disconnected.

Examples

Input:  n = 3, edges = [[0,1],[1,2],[2,0]]
Output: True

Input:  n = 4, edges = [[0,1],[1,2],[2,3]]
Output: False
Explanation: a path is a tree; trees have no cycles.

Input:  n = 6, edges = [[0,1],[2,3],[3,4],[4,2]]
Output: True
Explanation: 2 -> 3 -> 4 -> 2 is a cycle even though 0-1 and 5 are separate.

Constraints

  • 1 <= n <= 2 * 10**4, 0 <= len(edges) <= 5 * 10**4
  • Target O(V + E) time.

Goals

  • Detect a cycle in an undirected graph by remembering each node's parent
  • Distinguish the edge you arrived by from a genuine back edge
Starting Python…