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

Leetcode Problem 2608. Shortest Cycle in a Graph

2608. Shortest Cycle in a Graph

Leetcode Solutions

BFS Approach to Find the Shortest Cycle in a Graph

  1. Create an adjacency list to represent the graph.
  2. Initialize a variable to store the minimum cycle length, setting it to infinity.
  3. Iterate over each vertex in the graph.
  4. For each vertex, perform BFS: a. Initialize a visited array with values set to infinity, indicating unvisited nodes. b. Set the distance to the starting vertex to 0. c. Use a queue to perform BFS, starting with the current vertex. d. For each vertex dequeued, visit its neighbors: i. If the neighbor is unvisited, set its distance and enqueue it. ii. If the neighbor is visited and not the parent, calculate the cycle length. iii. Update the minimum cycle length if a shorter cycle is found.
  5. After BFS for all vertices, check if the minimum cycle length is less than infinity.
  6. If a cycle is found, return the minimum cycle length; otherwise, return -1.
UML Thumbnail

DFS Approach to Find the Shortest Cycle in a Graph

Ask Question

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

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...