class Solution:
def criticalConnections(self, n: int, connections: List[List[int]]) -> List[List[int]]:
"""tc O(V+E) sc O(V+E)
"""
g = collections.defaultdict(list)
for u,v in connections:
g[u].append(v)
g[v].append(u)
low = [-1] * n
dfn = [-1] * n
self.timestamp = 0
res = []
def dfs(cur, parent):
if dfn[cur] == -1:
dfn[cur] = self.timestamp
low[cur] = self.timestamp
self.timestamp += 1
for nei in g[cur]:
if parent!= None and nei == parent:
continue
elif dfn[nei] == -1:
dfs(nei, cur)
low[cur] = min(low[cur], low[nei])
else:
low[cur] = min(low[cur], dfn[nei])
# if low[cur] == dfn[cur] and cur != 0:
# res.append([cur,parent])
dfs(0, None)
res = []
for u,v in connections:
if dfn[u] < low[v] or dfn[v] < low[u]:
res.append([u,v])
return res