zoukankan      html  css  js  c++  java
  • 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
    
  • 相关阅读:
    谷粒商城所学知识点整理总结
    谷粒商城项目介绍
    JVM 中的垃圾回收
    对象的创建和分配
    JVM 中的异常
    JVM 中的StringTable
    一个 java 文件的执行过程详解
    复制表的方法
    从 Vue parseHTML 来学习正则表达式
    Visual Studio 2022 预览版下载来了(x64位)
  • 原文地址:https://www.cnblogs.com/panweiwei/p/14025375.html
Copyright © 2011-2022 走看看