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
- 70 lines of C++ from the credited upstream file 2204.cpp.
- 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:3 vector<int> distanceToCycle(int n, vector<vector<int>>& edges) {4 vector<int> ans(n);5 vector<vector<int>> graph(n);6 7 for (const vector<int>& edge : edges) {8 const int u = edge[0];9 const int v = edge[1];10 graph[u].push_back(v);11 graph[v].push_back(u);12 }13 14 15 16 vector<int> cycle;17 getRank(graph, 0, 0, vector<int>(n, NO_RANK), cycle);18 19 queue<int> q;20 vector<bool> seen(n);21 for (const int u : cycle) {22 q.push(u);23 seen[u] = true;24 }25 26 for (int step = 1; !q.empty(); ++step)27 for (int sz = q.size(); sz > 0; --sz) {28 const int u = q.front();29 q.pop();30 for (const int v : graph[u]) {31 if (seen[v])32 continue;33 q.push(v);34 seen[v] = true;35 ans[v] = step;36 }37 }38 39 return ans;40 }41 42 private:43 static constexpr int NO_RANK = -2;44 45 46 int getRank(const vector<vector<int>>& graph, int u, int currRank,47 vector<int>&& rank, vector<int>& cycle) {48 if (rank[u] != NO_RANK) 49 return rank[u];50 51 rank[u] = currRank;52 int minRank = currRank;53 54 for (const int v : graph[u]) {55 56 if (rank[v] == rank.size() || rank[v] == currRank - 1)57 continue;58 const int nextRank =59 getRank(graph, v, currRank + 1, std::move(rank), cycle);60 61 if (nextRank <= currRank)62 cycle.push_back(v);63 minRank = min(minRank, nextRank);64 }65 66 rank[u] = rank.size(); 67 return minRank;68 }69};70