1971. Find if Path Exists in Graph (Easy) - TengnanYao/daily_leetcode GitHub Wiki
class Solution:
def validPath(self, n: int, edges: List[List[int]], start: int, end: int) -> bool:
h = {}
for a, b in edges:
if a in h:
h[a].append(b)
else:
h[a] = [b]
if b in h:
h[b].append(a)
else:
h[b] = [a]
seen = set()
self.result = False
def dfs(start, end):
if not self.result:
if start == end:
self.result = True
return
if start in h:
seen.add(start)
for val in h[start]:
if val not in seen:
dfs(val, end)
dfs(start, end)
return self.result