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
- 66 lines of Java from the credited upstream file 2204.java.
- The implementation visibly relies on sequence storage, work queue.
- 6 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 public int[] distanceToCycle(int n, int[][] edges) {3 int[] ans = new int[n];4 List<Integer>[] graph = new List[n];5 Arrays.setAll(graph, i -> new ArrayList<>());6 7 for (int[] edge : edges) {8 final int u = edge[0];9 final int v = edge[1];10 graph[u].add(v);11 graph[v].add(u);12 }13 14 15 16 int[] rank = new int[n];17 Arrays.fill(rank, NO_RANK);18 List<Integer> cycle = new ArrayList<>();19 getRank(graph, 0, 0, rank, cycle);20 21 Queue<Integer> q = cycle.stream().collect(Collectors.toCollection(ArrayDeque::new));22 boolean[] seen = new boolean[n];23 for (final int u : cycle)24 seen[u] = true;25 26 for (int step = 1; !q.isEmpty(); ++step)27 for (int sz = q.size(); sz > 0; --sz) {28 final int u = q.poll();29 for (final int v : graph[u]) {30 if (seen[v])31 continue;32 q.offer(v);33 seen[v] = true;34 ans[v] = step;35 }36 }37 38 return ans;39 }40 41 private static final int NO_RANK = -2;42 43 44 private int getRank(List<Integer>[] graph, int u, int currRank, int[] rank, List<Integer> cycle) {45 if (rank[u] != NO_RANK) 46 return rank[u];47 48 rank[u] = currRank;49 int minRank = currRank;50 51 for (final int v : graph[u]) {52 53 if (rank[u] == rank.length || rank[v] == currRank - 1)54 continue;55 final int nextRank = getRank(graph, v, currRank + 1, rank, cycle);56 57 if (nextRank <= currRank)58 cycle.add(v);59 minRank = Math.min(minRank, nextRank);60 }61 62 rank[u] = rank.length; 63 return minRank;64 }65}66