- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# Program to find shortest cycle length holding target in python

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 -

- visited := a new set
- l := a list with element target.
- length := 0
- while l is non-empty, do
- length := length + 1
- nl := a new list
- for each u in l, do
- for each v in graph[u], do
- if v is same as target, then
- return length

- if v is visited, then
- go for the next iteration

- mark v as visited
- insert v at the end of nl

- if v is same as target, then

- for each v in graph[u], do
- l := nl

- return -1

Let us see the following implementation to get better understanding -

## Example

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],[2],[3],[0, 1],[]] target = 3 print(ob.solve(graph, target))

## Input

[[1, 4],[2],[3],[0, 1],[]]

## Output

3

- Related Questions & Answers
- Program to find length of shortest supersequence in Python
- Word Ladder (Length of shortest chain to reach a target word) in C++
- Shortest Distance to Target Color in C++
- Program to find length of shortest sublist with maximum frequent element with same frequency in Python
- Program to find intervals by merging target interval in Python
- Program to find length of longest matrix path length in Python
- Program to find number of K-Length sublists whose average is greater or same as target in python
- Program to find distance of shortest bridge between islands in Python
- Program to check whether odd length cycle is in a graph or not in Python
- Python Program to Find if Undirected Graph contains Cycle using BFS
- Python Program for Cycle Sort
- Program to find minimum length of lossy Run-Length Encoding in Python
- Program to find maximum profit we can make by holding and selling profit in Python
- Program to find minimum distance to the target element using Python
- Program to find shortest string after removing different adjacent bits in Python

Advertisements