Critical Connections in a Network LeetCode solution in Python

1
class Solution:
2
def criticalConnections(
3
self, n: int, connections: List[List[int]]
4
) -> List[List[int]]:
5

6
dic = collections.defaultdict(list)
7
for c in connections:
8
u, v = c
9
dic[u].append(v)
10
dic[v].append(u)
11

12
timer = 0
13

14
depth, lowest, parent, visited = (
15
[float("inf")] * n,
16
[float("inf")] * n,
17
[float("inf")] * n,
18
[False] * n,
19
)
20
res = []
21

22
def find(u):
23

24
nonlocal timer
25

26
visited[u] = True
27
depth[u], lowest[u] = timer, timer
28
timer += 1
29

30
for v in dic[u]:
31

32
if not visited[v]:
33
parent[v] = u
34
find(v)
35
if lowest[v] > depth[u]:
36
res.append([u, v])
37

38
if parent[u] != v:
39
lowest[u] = min(lowest[u], lowest[v])
40

41
find(0)
42
return res

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0