Search code examples
pythonalgorithmgraph-theory

Clarification Needed on Tarjan's Algorithm Implementation


I've been working on the Tarjan's algorithm for finding critical connections in a network, specifically applied to the problem outlined in this LeetCode challenge.

Here is my code:

class Solution:
    timer=0
    def criticalConnections(self, n: int, connections: List[List[int]]) -> List[List[int]]:
        graph=defaultdict(list)
        for a,b in connections:
            graph[a].append(b)
            graph[b].append(a)

        result=[]
        tin=[0]*n
        low=[0]*n
        visited=[False]*n
        def dfs(node,parent):
            self.timer+=1
            visited[node]=True
            tin[node]=self.timer
            low[node]=self.timer
            for child in graph[node]:
                if child==parent: continue
                if visited[child]:
                    low[node]=min(low[node],tin[child])
                else:
                    dfs(child,node)
                    low[node]=min(low[node],low[child])
                    if tin[node]<low[child]:
                        result.append([node,child])
        dfs(0,-1)
        return result

Why can't we use the condition if low[node]<low[child]: instead of if tin[node]<low[child]: to decided whether a bridge exists or not?

I understand that if the low of my child is bigger than my low, then it means that it can never be reached before me, hence indicating a bridge.


Solution

  • For someone who will stumble on this doubt in future. if low[node]<low[child]: would fail for this undirected graph [[0,1],[1,2],[2,0],[2,3],[1,3]] enter image description here