552. Distance to a Cycle in Undirected Graph

Given a positive integer n, representing the number of nodes in a connected undirected graph that contains exactly one cycle. The nodes are labeled from 0 to n - 1.

Additionally, you are given a 2D integer array edges, where edges[i] = [node1i, node2i] represents a bidirectional edge between node1i and node2i.

The distance between two nodes a and b is defined as the minimum number of edges required to travel from a to b.

Return an integer array answer of size n, where answer[i] represents the shortest distance from the i-th node to any node in the cycle.

Example 1:

Input: n = 8, edges = [[0,1],[1,3],[3,4],[4,2],[2,1],[5,3],[6,5],[7,6]]  

Output: [1,0,0,0,0,1,2,3]  

Explanation:

The nodes forming the cycle are 1, 2, 3, and 4.

Node 0 connects directly to 1, so its distance is 1.

Nodes 1, 2, 3, and 4 are part of the cycle, so their distance is 0.

Node 5 is connected to 3, so its distance is 1.

Node 6 is connected to 5, which is 1 away from the cycle, so its distance is 2.

Node 7 is connected to 6, which is 2 away, so its distance is 3.

Example 2:

Input: n = 10, edges = [[0,2],[2,3],[3,5],[5,1],[1,0],[4,1],[6,3],[7,6],[8,7],[9,8]]  

Output: [0,0,0,0,1,0,1,2,3,4]  

Explanation:

The cycle consists of nodes 0, 1, 2, 3, and 5.

Nodes in the cycle have a distance of 0.

Node 4 is connected to 1, so its distance is 1.

Node 6 is connected to 3, so its distance is 1.

Node 7 is connected to 6, which is 1 away, so its distance is 2.

Node 8 is connected to 7, making it 3 away.

Node 9 is connected to 8, making it 4 away.

Now Your Turn!

Pick the correct output for the given input

Input: n = 6, edges = [[0,1],[1,2],[2,3],[3,4],[4,1],[5,3]]  

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 3 ≤ n ≤ 105
  • edges.length == n
  • edges[i].length == 2
  • 0 ≤ node1i, node2i ≤ n - 1
  • node1i ≠ node2i
  • The graph is fully connected.
  • The graph contains exactly one cycle.
  • There is at most one edge between any two nodes.

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
class Solution {
public:
vector<int> distanceToCycle(int n, vector<vector<int>>& edges) {
}
};
 
Test Case

Input:

Edges
N