Problem Description
Given a connected undirected graph with n nodes and exactly one cycle, where nodes are numbered from 0 to n - 1, determine for each node the minimum distance to any node that is part of the cycle. The graph is represented by an edge list and the distance between nodes is defined as the minimum number of edges required to travel between them.
Key Insights
- The graph contains exactly one cycle; hence, all nodes not on the cycle are attached as trees.
- A strategy to identify the cycle is to iteratively remove leaf nodes (nodes with degree 1) until a cycle remains.
- Once the cycle nodes are identified, a multi-source BFS from these nodes efficiently computes the minimum distance for every node.
- Using a deque or queue makes the BFS traversal efficient for level-order propagation.
- The solution leverages both DFS-like (or topological peeling) and BFS techniques.
Space and Time Complexity
Time Complexity: O(n) – Each node and edge is processed a constant number of times during the leaf removal and BFS steps. Space Complexity: O(n) – Additional storage is used for the graph representation, degree count, and auxiliary queues/arrays.
Solution
The solution follows a two-step approach:
- Identify cycle nodes by iterative leaf removal. Build an adjacency list from the edges and track the degree of each node. Enqueue nodes with degree 1 and remove them until no leaves remain. The remaining nodes are part of the cycle.
- Perform a multi-source BFS starting from all cycle nodes (distance assigned as 0). Propagate the distance to every other node in the graph by updating the neighbor’s distance if not already visited.
This approach simplifies cycle detection without needing complex DFS backtracking and then efficiently computes distances using breadth-first traversal.