Skip to content

Commit 3e30766

Browse files
committed
add problem 1466
1 parent f688941 commit 3e30766

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
class Solution:
2+
def minReorder(self, n: int, connections: List[List[int]]) -> int:
3+
edges = {(a,b) for a, b in connections}
4+
neighbors = defaultdict(list)
5+
visit = set()
6+
changes = 0
7+
8+
for a, b in connections:
9+
neighbors[a].append(b)
10+
neighbors[b].append(a)
11+
12+
def dfs(city):
13+
nonlocal changes
14+
15+
for neighbor in neighbors[city]:
16+
if neighbor in visit:
17+
continue
18+
# check if this neighbor can reach city 0
19+
if (neighbor, city) not in edges:
20+
changes += 1
21+
visit.add(neighbor)
22+
dfs(neighbor)
23+
visit.add(0)
24+
dfs(0)
25+
return changes

0 commit comments

Comments
 (0)