forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfind-if-path-exists-in-graph.py
112 lines (102 loc) · 2.99 KB
/
find-if-path-exists-in-graph.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
# Time: O(|V| + |E|)
# Space: O(|V| + |E|)
import collections
# bi-bfs solution
class Solution(object):
def validPath(self, n, edges, start, end):
"""
:type n: int
:type edges: List[List[int]]
:type start: int
:type end: int
:rtype: bool
"""
def bi_bfs(adj, start, target):
left, right = {start}, {target}
lookup = set()
steps = 0
while left:
for pos in left:
lookup.add(pos)
new_left = set()
for pos in left:
if pos in right:
return steps
for nei in adj[pos]:
if nei in lookup:
continue
new_left.add(nei)
left = new_left
steps += 1
if len(left) > len(right):
left, right = right, left
return -1
adj = collections.defaultdict(list)
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
return bi_bfs(adj, start, end) >= 0
# Time: O(|V| + |E|)
# Space: O(|V| + |E|)
# bfs solution
class Solution2(object):
def validPath(self, n, edges, start, end):
"""
:type n: int
:type edges: List[List[int]]
:type start: int
:type end: int
:rtype: bool
"""
def bfs(adj, start, target):
q = [start]
lookup = set(q)
steps = 0
while q:
new_q = []
for pos in q:
if pos == target:
return steps
for nei in adj[pos]:
if nei in lookup:
continue
lookup.add(nei)
new_q.append(nei)
q = new_q
steps += 1
return -1
adj = collections.defaultdict(list)
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
return bfs(adj, start, end) >= 0
# Time: O(|V| + |E|)
# Space: O(|V| + |E|)
# dfs solution
class Solution3(object):
def validPath(self, n, edges, start, end):
"""
:type n: int
:type edges: List[List[int]]
:type start: int
:type end: int
:rtype: bool
"""
def dfs(adj, start, target):
stk = [start]
lookup = set(stk)
while stk:
pos = stk.pop()
if pos == target:
return True
for nei in reversed(adj[pos]):
if nei in lookup:
continue
lookup.add(nei)
stk.append(nei)
return False
adj = collections.defaultdict(list)
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
return dfs(adj, start, end)