Problem solution · Python

Distance to a Cycle in Undirected Graph

Distance to a Cycle in Undirected Graph: a Python solution using breadth-first search. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Breadth-first search
Source
walkccc LeetCode Solutions
Length
54 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Breadth-first search

For Distance to a Cycle in Undirected Graph, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.

  1. Model each valid configuration as a state and each legal move as an edge.
  2. Seed the queue with the starting state and mark it immediately.
  3. Expand each state once, recording distance or reachability for unseen neighbours.

Code notes

  • 54 lines of Python from the credited upstream file 2204.py.
  • The implementation visibly relies on sequence storage, ordered lookup, work queue.
  • No explicit loop blocks detected.

Complexity

Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeDistance to a Cycle in Undirected Graph · PythonPython
Use this to learn the idea, then write your own version.
class Solution:  def distanceToCycle(self, n: int, edges: list[list[int]]) -> list[int]:    ans = [0] * n    graph = [[] for _ in range(n)]     for u, v in edges:      graph[u].append(v)      graph[v].append(u)     NO_RANK = -2     # The minRank that u can reach with forward edges    def getRank(u: int, currRank: int, rank: list[int]) -> int:      if rank[u] != NO_RANK:  # The rank is already determined        return rank[u]       rank[u] = currRank      minRank = currRank       for v in graph[u]:        # Visited or parent (that's why NO_RANK = -2 instead of -1)        if rank[v] == len(rank) or rank[v] == currRank - 1:          continue        nextRank = getRank(v, currRank + 1, rank)        # NextRank should > currRank if there's no cycle        if nextRank <= currRank:          cycle.append(v)        minRank = min(minRank, nextRank)       rank[u] = len(rank)  # Mark as visited.      return minRank     # rank[i] := the minimum node that node i can reach with forward edges    # Initialize with NO_RANK = -2 to indicate not visited.    cycle = []    getRank(0, 0, [NO_RANK] * n)     q = collections.deque(cycle)    seen = set(cycle)     step = 1    while q:      for _ in range(len(q)):        u = q.popleft()        for v in graph[u]:          if v in seen:            continue          q.append(v)          seen.add(v)          ans[v] = step      step += 1     return ans 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗