-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1466.py
More file actions
71 lines (52 loc) · 1.7 KB
/
1466.py
File metadata and controls
71 lines (52 loc) · 1.7 KB
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
class Solution(object):
def minReorder(self, n, connections):
"""
:type n: int
:type connections: List[List[int]]
:rtype: int
"""
from collections import defaultdict
neighbors = defaultdict(list)
visited = set()
# reverse_destinations = set()
edges={(a,b) for a,b in connections}
zero_set = set()
changes = 0
for src, dst in connections:
neighbors[src].append(dst)
neighbors[dst].append(src)
def dfs(curr_node):
nonlocal changes
for i in neighbors[curr_node]:
if i not in visited:
if (i, curr_node) not in edges:
changes += 1
visited.add(i)
dfs(i)
return
visited.add(0)
dfs(0)
return changes
# class Solution:
# def minReorder(self, n: int, connections: List[List[int]]) -> int:
# 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
# if (neighbor,city) not in edges:
# changes +=1
# visit.add(neighbor)
# dfs(neighbor)
# visit.add(0)
# dfs(0)
# return changes
s = Solution()
print(s.minReorder(6, [[0,1],[1,3],[2,3],[4,0],[4,5]]))