797. 所有可能的路径






代码一:DFS回溯

class Solution(object):
    # 方法一:DFS
    def allPathsSourceTarget(self, graph):
        """
        :type graph: List[List[int]]
        :rtype: List[List[int]]
        """
        if not graph[0]:
            return []
        res = []
        n = len(graph)
        self.dfs(graph, 0, n - 1, [0], res)
        return res

    def dfs(self, graph, cur, end, temp, res):
        # 递归出口:当前节点是n-1时,说明找到一条新路径
        if temp[-1] == end:
            res.append(temp)
            return
        # 顺着当前节点往下走
        for i in graph[cur]:
            self.dfs(graph, i, end, temp + [i], res)

代码二:BFS

class Solution(object):
    def allPathsSourceTarget(self, graph):
        """
        :type graph: List[List[int]]
        :rtype: List[List[int]]
        """
        # 特判
        if not graph[0]:
            return []
        # 路径终点
        end = len(graph) - 1
        res = []
        # 队列初始化
        nodeQueue = [0]
        pathQueue = [[0]]
        while nodeQueue:
            node = nodeQueue.pop(0)
            path = pathQueue.pop(0)
            # 遍历当前节点能达到的所有节点
            for i in graph[node]:
                # 若当前节点是终点,则找到一条新路径
                if i == end:
                    res.append(path + [i])
                # 否则,当前节点先入队,并更新当前路径
                else:
                    nodeQueue.append(i)
                    pathQueue.append(path + [i])
        return res
posted @   人间烟火地三鲜  阅读(209)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
点击右上角即可分享
微信分享提示