I'm trying to translate a C++ graph algorithm into Python.
The C++ version finds all bridge edges in an undirected graph using Tarjan's DFS (low-link values).
My Python code is supposed to collect the weights of all bridge edges, sort them, and compute two sums (sum_max and sum_min) by taking alternating elements from the sorted list.
However, for some inputs, the Python output doesn't match the C++ output.
Here is the relevant part of my Python code:
g = [[] for _ in range(N)] vis = [False] * N disc = [0] * N low = [0] * N a = [0] * N bridgeEdge = [] tim = 0 def dfs(node, par): global tim vis[node] = True tim += 1 disc[node] = low[node] = tim for nxt, idx in g[node]: if nxt == par: continue if not vis[nxt]: dfs(nxt, node) if low[nxt] > disc[node]: bridgeEdge.append(a[idx]) low[node] = min(low[node], low[nxt]) else: low[node] = min(low[node], disc[nxt]) After running DFS starting from node 1, I sort bridgeEdge and compute:
bridgeEdge.sort() sum_max = sum(bridgeEdge[i] for i in range(len(bridgeEdge)-1, -1, -2)) sum_min = sum(bridgeEdge[i] for i in range(len(bridgeEdge)-2, -1, -2)) Problem
My Python outputs differ from the C++ version when the graph is disconnected or when edges form cycles.
Questions
Is my DFS implementation missing a necessary condition from the C++ code?
Do I need to run
dfs()on all unvisited nodes instead of justdfs(1, -1)?Is there a Python-specific issue involving recursion depth or global access that may affect the result?
Any help is appreciated!