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.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- 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.
Use this to learn the idea, then write your own version.
1class Solution:2 def distanceToCycle(self, n: int, edges: list[list[int]]) -> list[int]:3 ans = [0] * n4 graph = [[] for _ in range(n)]5 6 for u, v in edges:7 graph[u].append(v)8 graph[v].append(u)9 10 NO_RANK = -211 12 13 def getRank(u: int, currRank: int, rank: list[int]) -> int:14 if rank[u] != NO_RANK: 15 return rank[u]16 17 rank[u] = currRank18 minRank = currRank19 20 for v in graph[u]:21 22 if rank[v] == len(rank) or rank[v] == currRank - 1:23 continue24 nextRank = getRank(v, currRank + 1, rank)25 26 if nextRank <= currRank:27 cycle.append(v)28 minRank = min(minRank, nextRank)29 30 rank[u] = len(rank) 31 return minRank32 33 34 35 cycle = []36 getRank(0, 0, [NO_RANK] * n)37 38 q = collections.deque(cycle)39 seen = set(cycle)40 41 step = 142 while q:43 for _ in range(len(q)):44 u = q.popleft()45 for v in graph[u]:46 if v in seen:47 continue48 q.append(v)49 seen.add(v)50 ans[v] = step51 step += 152 53 return ans54