【题目】
【代码】
【方法1】思路:广度优先搜索bfs
class Solution:
def findWhetherExistsPath(self, n: int, graph: List[List[int]], start: int, target: int) -> bool:
dic={}
for x,y in graph:
if x not in dic:
dic[x]=[]
dic[x].append(y)
queue=[start]
while queue:
item=queue.pop(0)
if item==target:
return True
if item not in dic:
continue
for son in dic[item]:
queue.append(son)
return False
【方法2】思路:深度优先搜索dfs
class Solution:
def findWhetherExistsPath(self, n: int, graph: List[List[int]], start: int, target: int) -> bool:
dic={}
for x,y in graph:
if x not in dic:
dic[x]=[]
dic[x].append(y)
def dfs(x,visited):
if x==target:
return True
if visited[x]:
return False
visited[x]=True
ans=False
if x in dic:
for son in dic[x]:
ans=ans or dfs(son,visited)
return ans
return dfs(start,[False]*n)