1192. Critical Connections in a Network

1192. Critical Connections in a Network

class Solution:
    def criticalConnections(self, n: int, connections: List[List[int]]) -> List[List[int]]:
        graph=[[]for i in range(n)]

        for n1,n2 in connections:
            graph[n1].append(n2)
            graph[n2].append(n1)

        lows=[n]*n
        critical=[]

        def dfs(node,dt,p):
            if lows[node]==n:
                lows[node]=dt
                for nei in graph[node]:
                    if nei !=p:
                        etc=dt+1
                        # 进入dfs一开始赋的值就是dt+1
                        # 所以下面可以取等号
                        atc=dfs(nei,etc,node)
                        if atc>=etc:
                            critical.append((node,nei))
                        lows[node]=min(lows[node],atc)
        
            return lows[node]
        dfs(n-1,0,-1)
        return critical

你可能感兴趣的:(leetcode)