forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
reorder-routes-to-make-all-paths-lead-to-the-city-zero.py
56 lines (48 loc) · 1.4 KB
/
reorder-routes-to-make-all-paths-lead-to-the-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
48
49
50
51
52
53
54
55
56
# Time: O(n)
# Space: O(n)
import collections
class Solution(object):
def minReorder(self, n, connections):
"""
:type n: int
:type connections: List[List[int]]
:rtype: int
"""
lookup, graph = set(), collections.defaultdict(list)
for u, v in connections:
lookup.add(u*n+v)
graph[v].append(u)
graph[u].append(v)
result = 0
stk = [(-1, 0)]
while stk:
parent, u = stk.pop()
result += (parent*n+u in lookup)
for v in reversed(graph[u]):
if v == parent:
continue
stk.append((u, v))
return result
# Time: O(n)
# Space: O(n)
import collections
class Solution2(object):
def minReorder(self, n, connections):
"""
:type n: int
:type connections: List[List[int]]
:rtype: int
"""
def dfs(n, lookup, graph, parent, u):
result = (parent*n+u in lookup)
for v in graph[u]:
if v == parent:
continue
result += dfs(n, lookup, graph, u, v)
return result
lookup, graph = set(), collections.defaultdict(list)
for u, v in connections:
lookup.add(u*n+v)
graph[v].append(u)
graph[u].append(v)
return dfs(n, lookup, graph, -1, 0)