Longest Loop in a Conveyor Network

Implement longestLoop

A conveyor network has n stations; every station has at most one outgoing conveyor (so its adjacency list is empty or holds a single station). A loop is a route along the conveyors that returns to its starting station. Find the length of the longest loop, or -1 if the network has none.

Because each station has at most one exit, walks never branch, which makes it possible to measure a loop by comparing step numbers instead of exploring the whole graph.

Example 1:

Input: graph = [[1],[2],[0],[4],[5],[6],[7],[4]]

Output: 4

Example 2:

Input: graph = [[1],[2],[]]

Output: -1

Example 3:

Input: graph = [[0]]

Output: 1

+ 14 hidden test cases run on Submit.

Constraints:

  • ●1 ≤ n ≤ 10 stations numbered 0 … n-1; graph[u] is the adjacency list of a directed graph in which every station has at most one outgoing conveyor: graph[u] is either empty or holds exactly one station
  • ●A conveyor from a station to itself is allowed (a loop of length 1)
  • ●A loop is a route that follows the conveyors and returns to its starting station; its length is the number of conveyors used
  • ●Return the length of the longest loop, or -1 if there is none

graph =

[[1], [2], [0], [4], [5], [6], [7], [4]]