Leetcode Problem 2360. Longest Cycle in a Graph

2360. Longest Cycle in a Graph

Leetcode Solutions

Depth First Search to Find the Longest Cycle

Algorithm

  1. Initialize answer to -1.
  2. Initialize n to the length of edges.
  3. Create a visit array to track visited nodes.
  4. Iterate over all nodes:
    • If a node i is unvisited, start DFS from i.
    • In DFS:
      • Mark node as visited.
      • Get neighbor using edges[node].
      • If neighbor is unvisited, set dist[neighbor] and recurse with neighbor.
      • If neighbor is visited and present in dist, update answer with the cycle length.
  5. Return answer.
UML Thumbnail

Kahn's Algorithm to Detect Cycles

Ask Question

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

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...