-3

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

  1. Is my DFS implementation missing a necessary condition from the C++ code?

  2. Do I need to run dfs() on all unvisited nodes instead of just dfs(1, -1)?

  3. Is there a Python-specific issue involving recursion depth or global access that may affect the result?

Any help is appreciated!

New contributor
user31987140 is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
4
  • 1
    Could you please include the C++ code? Commented 9 hours ago
  • Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. Commented 9 hours ago
  • How to Ask and minimal reproducible example Commented 7 hours ago
  • On 3: If you have runaway recursion, your code will throw an exception; it won't silently return the wrong result. Commented 5 hours ago

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.