bugfree Icon
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course

Leetcode Problem 2204. Distance to a Cycle in Undirected Graph

2204. Distance to a Cycle in Undirected Graph

Leetcode Solutions

Topological Sort + BFS with Multiple Vertices

  1. Create a graph representation and an in-degree map from the given edges.
  2. Initialize a set s with all node indices and a deque dq.
  3. Add all nodes with in-degree 1 (leaves) to dq.
  4. Perform a modified topological sort by removing leaves from s and updating in-degrees until dq is empty, leaving only cycle nodes in s.
  5. Initialize a result list res with -1 for all nodes.
  6. Add all nodes in s (cycle nodes) to dq and set their distance to 0 in res.
  7. Perform BFS from the nodes in dq, updating the distance for each node in res.
  8. Return the res list containing the minimum distances.
UML Thumbnail

Cycle Detection + BFS

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...