【题目】

【代码】
【方法1】广度优先搜索

class Solution:
def validPath(self, n: int, edges: List[List[int]], source: int, destination: int) -> bool:
if edges==[] or source==destination:return True
dic={}
for a,b in edges:
if a not in dic:
dic[a]=[]
dic[a].append(b)
if b not in dic:
dic[b]=[]
dic[b].append(a)
queue=[source]
visited=[False]*n
ans=False
while queue:
item=queue.pop(0)
visited[item]=True
if item in dic:
if destination in dic[item]:
ans=True
break
for son in dic[item]:
if visited[son]==False:
queue.append(son)
return ans
【方法2】深度优先遍历

class Solution:
def validPath(self, n: int, edges: List[List[int]], source: int, destination: int) -> bool:
if edges==[] or source==destination:return True
dic={}
for a,b in edges:
if a not in dic:
dic[a]=[]
dic[a].append(b)
if b not in dic:
dic[b]=[]
dic[b].append(a)
ans=False
def dfs(x,visited):
global ans
visited[x]=True
if x==destination:
ans=True
return True
res=False
for son in dic[x]:
if visited[son]==False:
res =res or dfs(son,visited)
return res
return dfs(source,[False]*n)
【方法3】dfs

class Solution:
def validPath(self, n: int, edges: List[List[int]], source: int, destination: int) -> bool:
gra=[[] for _ in range(n)]
for x,y in edges:
gra[x].append(y)
gra[y].append(x)
if destination in gra[source]:
return True
v=set()
flag=False
def dfs(st):
nonlocal flag
if st==destination:
flag=True
return flag
for i in gra[st]:
if i in v:
continue
v.add(i)
dfs(i)
dfs(source)
return flag
这篇博客探讨了如何在图中寻找从源节点到目标节点的有效路径。提供了两种算法实现:广度优先搜索(BFS)和深度优先遍历(DFS)。在给定的代码中,当边为空或者源节点等于目标节点时,直接返回真。否则,通过构建邻接表来表示图,并用队列进行BFS,或者递归进行DFS,以判断是否存在有效路径。
720

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



