-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathShortestCycleinaGraph_Day73.py
More file actions
32 lines (25 loc) · 978 Bytes
/
ShortestCycleinaGraph_Day73.py
File metadata and controls
32 lines (25 loc) · 978 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
from collections import defaultdict, deque
from typing import List
class Solution:
def findShortestCycle(self, n: int, edges: List[List[int]]) -> int:
graph = defaultdict(list)
# adjacency list
for u, v in edges:
graph[u].append(v)
graph[v].append(u)
min_cycle = float("inf")
for start in range(n):
dist = [-1] * n
parent = [-1] * n
q = deque([start])
dist[start] = 0
while q:
node = q.popleft()
for nei in graph[node]:
if dist[nei] == -1: # not visited
dist[nei] = dist[node] + 1
parent[nei] = node
q.append(nei)
elif parent[node] != nei: # found a cycle
min_cycle = min(min_cycle, dist[node] + dist[nei] + 1)
return -1 if min_cycle == float("inf") else min_cycle