Skip to content

Commit 8fe7b6f

Browse files
authored
Update find-if-path-exists-in-graph.py
1 parent fc336d3 commit 8fe7b6f

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

Python/find-if-path-exists-in-graph.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,3 +77,36 @@ def bfs(adj, start, target):
7777
adj[u].append(v)
7878
adj[v].append(u)
7979
return bfs(adj, start, end) >= 0
80+
81+
82+
# Time: O(|V| + |E|)
83+
# Space: O(|V| + |E|)
84+
# dfs solution
85+
class Solution3(object):
86+
def validPath(self, n, edges, start, end):
87+
"""
88+
:type n: int
89+
:type edges: List[List[int]]
90+
:type start: int
91+
:type end: int
92+
:rtype: bool
93+
"""
94+
def dfs(adj, start, target):
95+
stk = [start]
96+
lookup = set(stk)
97+
while stk:
98+
pos = stk.pop()
99+
if pos == target:
100+
return True
101+
for nei in reversed(adj[pos]):
102+
if nei in lookup:
103+
continue
104+
lookup.add(nei)
105+
stk.append(nei)
106+
return False
107+
108+
adj = collections.defaultdict(list)
109+
for u, v in edges:
110+
adj[u].append(v)
111+
adj[v].append(u)
112+
return dfs(adj, start, end)

0 commit comments

Comments
 (0)