- 根据 connections 建立无向树
- 从 0 开始深搜,每次调用 dfs 时判断路径方向是否正确
class Solution:
def minReorder(self, n: int, connections: List[List[int]]) -> int:
to = defaultdict(set)
edge = defaultdict(list)
for con in connections:
edge[con[0]].append(con[1])
edge[con[1]].append(con[0])
to[con[0]].add(con[1])
ans = 0
def dfs(node, fa):
nonlocal ans
for ch in edge[node]:
if ch == fa:
continue
if ch in to[node]:
ans += 1
dfs(ch, node)
dfs(0, -1)
return ans