[Swift-2019力扣杯春季初赛]4. 从始点到终点的所有路径
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
给定有向图的边 edges
,以及该图的始点 source
和目标终点 destination
,确定从始点 source
出发的所有路径是否最终结束于目标终点 destination
,即:
- 从始点
source
到目标终点destination
存在至少一条路径 - 如果存在从始点
source
到没有出边的节点的路径,则该节点就是路径终点。 - 从始点
source
到目标终点destination
可能路径数是有限数字
当从始点 source
出发的所有路径都可以到达目标终点 destination
时返回 true
,否则返回 false
。
示例 1:
输入:n = 3, edges = [[0,1],[0,2]], source = 0, destination = 2 输出:false 说明:节点 1 和节点 2 都可以到达,但也会卡在那里。
示例 2:
输入:n = 4, edges = [[0,1],[0,3],[1,2],[2,1]], source = 0, destination = 3 输出:false 说明:有两种可能:在节点 3 处结束,或是在节点 1 和节点 2 之间无限循环。
示例 3:
输入:n = 4, edges = [[0,1],[0,2],[1,3],[2,3]], source = 0, destination = 3 输出:true
示例 4:
输入:n = 3, edges = [[0,1],[1,1],[1,2]], source = 0, destination = 2 输出:false 说明:从始点出发的所有路径都在目标终点结束,但存在无限多的路径,如 0-1-2,0-1-1-2,0-1-1-1-2,0-1-1-1-1-2 等。
示例 5:
输入:n = 2, edges = [[0,1],[1,1]], source = 0, destination = 1 输出:false 说明:在目标节点上存在无限的自环。
提示:
- 给定的图中可能带有自环和平行边。
- 图中的节点数
n
介于1
和10000
之间。 - 图中的边数在
0
到10000
之间。 0 <= edges.length <= 10000
edges[i].length == 2
0 <= source <= n - 1
0 <= destination <= n - 1
764ms
1 class Solution { 2 func leadsToDestination(_ n: Int, _ edges: [[Int]], _ source: Int, _ destination: Int) -> Bool { 3 var graph:[Int:[Int]] = [Int:[Int]]() 4 var path:Set<Int> = Set<Int>() 5 var qu:[Int] = [Int]() 6 for e in edges 7 { 8 graph[e[0],default:[Int]()].append(e[1]) 9 } 10 if graph[destination] != nil 11 { 12 return false 13 } 14 if n == 1 15 { 16 return true 17 } 18 path.insert(source) 19 if !dfs(&graph,&path,source,destination) 20 { 21 return false 22 } 23 return true 24 } 25 26 func dfs(_ graph:inout [Int:[Int]],_ path:inout Set<Int>,_ last:Int,_ destination:Int) -> Bool 27 { 28 if graph[last] == nil 29 { 30 return false 31 } 32 for e in graph[last,default:[Int]()] 33 { 34 if path.contains(e) 35 { 36 return false 37 } 38 else 39 { 40 if e == destination 41 { 42 continue 43 } 44 path.insert(e) 45 if !dfs(&graph,&path,e,destination) 46 { 47 return false 48 } 49 path.remove(e) 50 } 51 } 52 return true 53 } 54 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术