LeetCode 题解工作台

所有可能的路径

给你一个有 n 个节点的 有向无环图(DAG) ,请你找出从节点 0 到节点 n-1 的所有路径并输出( 不要求按特定顺序 ) graph[i] 是一个从节点 i 可以访问的所有节点的列表(即从节点 i 到节点 graph[i][j] 存在一条有向边)。 示例 1: 输入: graph = [[1,…

category

4

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

中等 · 图·DFS·traversal

bolt

答案摘要

class Solution: def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]:

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 图·DFS·traversal 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个有 n 个节点的 有向无环图(DAG),请你找出从节点 0 到节点 n-1 的所有路径并输出(不要求按特定顺序

 graph[i] 是一个从节点 i 可以访问的所有节点的列表(即从节点 i 到节点 graph[i][j]存在一条有向边)。

 

示例 1:

输入:graph = [[1,2],[3],[3],[]]
输出:[[0,1,3],[0,2,3]]
解释:有两条路径 0 -> 1 -> 3 和 0 -> 2 -> 3

示例 2:

输入:graph = [[4,3,1],[3,2,4],[3],[4],[]]
输出:[[0,4],[0,3,4],[0,1,3,4],[0,1,2,3,4],[0,1,4]]

 

提示:

  • n == graph.length
  • 2 <= n <= 15
  • 0 <= graph[i][j] < n
  • graph[i][j] != i(即不存在自环)
  • graph[i] 中的所有元素 互不相同
  • 保证输入为 有向无环图(DAG)

 

lightbulb

解题思路

方法一

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution:
    def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]:
        n = len(graph)
        q = deque([[0]])
        ans = []
        while q:
            path = q.popleft()
            u = path[-1]
            if u == n - 1:
                ans.append(path)
                continue
            for v in graph[u]:
                q.append(path + [v])
        return ans
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Candidates should demonstrate understanding of graph traversal, especially DFS and backtracking.

  • question_mark

    Check if the candidate can handle path construction and backtracking efficiently.

  • question_mark

    Ensure the candidate explains edge cases, such as when no path exists or when the graph is fully connected.

warning

常见陷阱

外企场景
  • error

    Overcomplicating the solution with unnecessary algorithms like BFS when DFS is sufficient.

  • error

    Failing to handle the backtracking step correctly, leading to missing paths.

  • error

    Not managing memory effectively for larger graphs, which could cause stack overflow or excessive space usage.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Limit the number of nodes (n) to test edge cases and ensure efficient backtracking.

  • arrow_right_alt

    Modify the graph to add additional constraints, like limiting path lengths or adding weighted edges.

  • arrow_right_alt

    Implement a variant where paths must be ordered based on node labels.

help

常见问题

外企场景

所有可能的路径题解:图·DFS·traversal | LeetCode #797 中等