VISUALGO//PROBLEMS
reorder routes to make all paths lead to the city zero · graphs – dfsmedium
LeetCode #1466
graph
012345
city
·
flips
·
stack
·
·
·
·
·
·
ELEMENTS
n
connections
Python
def minReorder(n: int, connections: list[list[int]]) -> int:
    adj = [[] for _ in range(n)]
    for a, b in connections:
        adj[a].append((b, 1))  # a -> b points away from a: reverse if walked outward
        adj[b].append((a, 0))
    seen = [False] * n
    seen[0] = True
    stack = [0]
    flips = 0
    while stack:
        city = stack.pop()
        for nxt, away in adj[city]:
            if not seen[nxt]:
                seen[nxt] = True
                flips += away
                stack.append(nxt)
    return flips