Suppose we have adjacency list of a directed graph, where each list at index i is represented connected nodes from node i. We also have a target value. We have to find the length of a shortest cycle that contains the target. If there is no solution return -1.
So, if the input is like
target = 3., then the output will be 3, as the cycle is nodes 1 -> 2 -> 3 -> 1. Note there is another cycle 0 -> 1 -> 2 -> 3 -> 0, but this is not shortest.
To solve this, we will follow these steps -
Let us see the following implementation to get better understanding -
class Solution: def solve(self, graph, target): visited = set() l = [target] length = 0 while l: length += 1 nl =  for u in l: for v in graph[u]: if v == target: return length if v in visited: continue visited.add(v) nl.append(v) l = nl return -1 ob = Solution() graph = [[1, 4],,,[0, 1],] target = 3 print(ob.solve(graph, target))
[[1, 4],,,[0, 1],]