【题目】

【代码】
【方法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)
本文探讨了两种常用的图搜索算法——广度优先搜索(BFS)和深度优先搜索(DFS),通过实例展示了如何使用它们在给定的矩阵图中查找从起点到终点的路径。两种方法的实现细节和应用场景对比,帮助理解在实际编程中如何选择最合适的搜索策略。
167

被折叠的 条评论
为什么被折叠?



