Similar Problems
Similar Problems not available
Shortest Cycle In A Graph - Leetcode Solution
Companies:
LeetCode: Shortest Cycle In A Graph Leetcode Solution
Difficulty: Hard
Topics: graph breadth-first-search
The problem "Shortest Cycle In A Graph" on LeetCode can be solved using Breadth-First Search (BFS) on a graph.
The problem statement is: Given an undirected graph, return the length of the shortest cycle that can be formed within the graph. If no cycle exists, return -1.
Algorithm:
- Initialize a variable "cycle_length" to -1.
- For each node in the graph, perform BFS starting from that node.
- During the BFS, maintain a set of visited nodes, a queue of nodes to visit next, and a parent of each node.
- If we encounter a node that is already visited and it is not the parent of the current node, we have found a cycle. Calculate the length of the cycle and update the "cycle_length" variable.
- Continue BFS until all nodes have been visited.
- Return the "cycle_length" variable.
Code:
Here is the Python code that implements the above algorithm:
from collections import deque
class Solution:
def shortestCycle(self, graph: List[List[int]]) -> int:
n = len(graph)
cycle_length = -1
# Perform BFS from each node
for i in range(n):
visited = set()
q = deque()
q.append((i, 0))
visited.add(i)
while q:
node, level = q.popleft()
for nei in graph[node]:
if nei not in visited:
visited.add(nei)
q.append((nei, level+1))
elif nei != node:
# Cycle found
cycle_len = level+1
if cycle_length == -1:
cycle_length = cycle_len
else:
cycle_length = min(cycle_length, cycle_len)
return cycle_length
Time Complexity: O(V*(V+E)), where V is the number of vertices and E is the number of edges in the graph.
Space Complexity: O(V+E), where V is the number of vertices and E is the number of edges in the graph.
Shortest Cycle In A Graph Solution Code
1