题目:原题链接(中等)
标签:图、有向图、深度优先搜索
解法 | 时间复杂度 | 空间复杂度 | 执行用时 |
---|---|---|---|
Ans 1 (Python) | – | – | 92ms (10.46%) |
Ans 2 (Python) | |||
Ans 3 (Python) |
解法一:
class Solution:
def leadsToDestination(self, n: int, edges: List[List[int]], source: int, destination: int) -> bool:
graph = collections.defaultdict(set)
for edge in edges:
graph[edge[0]].add(edge[1])
# 如果终点还有向外的点
if len(graph[destination]) > 0:
return False
visited = {source}
def dfs(now):
if now == destination:
return True
if len(graph[now]) == 0:
return False
for nxt in graph[now]:
if nxt in visited:
return False
visited.add(nxt)
if not dfs(nxt):
return False
visited.remove(nxt)
return True
return dfs(source)