-
Notifications
You must be signed in to change notification settings - Fork 0
/
reorder_routes_to_make_all_paths_lead_to_city_zero.py
47 lines (38 loc) · 1.62 KB
/
reorder_routes_to_make_all_paths_lead_to_city_zero.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
from typing import List
class Solution:
"""
Task:
There are n cities numbered from 0 to n - 1 and n - 1 roads such that there is only one way to travel
between two different cities (this network form a tree).
Last year, The ministry of transport decided to orient the roads
in one direction because they are too narrow.
Roads are represented by connections where connections[i] = [ai, bi] represents a road from city ai to city bi.
This year, there will be a big event in the capital (city 0), and many people want to travel to this city.
Your task consists of reorienting some roads such that each city can visit the city 0.
Return the minimum number of edges changed.
It's guaranteed that each city can reach city 0 after reorder
"""
def minReorder(self, n: int, connections: List[List[int]]) -> int:
# Start at city-0
# recursively check its neighbors
# count ongoing edges
edges = {(a, b) for a, b in connections}
neighbors = { city:[] for city in range(n)}
visit = set()
changes = 0
for a, b in connections:
neighbors[a].append(b)
neighbors[b].append(a)
def dfs(city):
nonlocal edges, neighbors, visit, changes
for neighbor in neighbors[city]:
if neighbor in visit:
continue
# check if this neighbor can reach city 0
if (neighbor, city) not in edges:
changes += 1
visit.add(neighbor)
dfs(neighbor)
visit.add(0)
dfs(0)
return changes