我的代码(从源到目标的所有路径)中有什么问题?

发布于 2025-02-05 18:17:11 字数 1209 浏览 1 评论 0原文

问题声明: 问题链接

给定标记为0到n -1的n个节点的定向无环图(DAG),找到从节点0到节点n -1的所有可能路径,然后以任何顺序返回。

给出图表如下:图[i]是您可以的所有节点的列表 从节点i访问(即,有一个从节点I到节点的指向边缘 图[i] [j])。

输入:

[[1,2],[3],[3],[]]

输出:

[[0,1,3],[0,2,3]]

这是我的代码:

class Solution:
def allPathsSourceTargetUtil(self, n, graph, visited, ans):
    visited.append(n)
    
    if n == len(graph)-1:
        ans.append(visited)
        print(ans)
    else:
        for i in graph[n]:
            self.allPathsSourceTargetUtil(i, graph, visited, ans)
        
            visited.pop()
    
    
def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]:
    ans  = []
    visited = []
    n = 0
    
    self.allPathsSourceTargetUtil(n, graph, visited, ans)
    
    return ans

这是输入:

[[1,2],[3],[3],[]]

实际输出:

[[0,1,3],[0,2,3]]

但是我从代码中获得此输出:

[[0, 1, 3]]
[[0, 2, 3], [0, 2, 3]]

[[0],[0]]

请帮助我在此代码中找出问题。

Problem statement:
Question link

Given a directed acyclic graph (DAG) of n nodes labeled from 0 to n - 1, find all possible paths from node 0 to node n - 1 and return them in any order.

The graph is given as follows: graph[i] is a list of all nodes you can
visit from node i (i.e., there is a directed edge from node i to node
graph[i][j]).

Input:

[[1,2],[3],[3],[]]

Output:

[[0,1,3],[0,2,3]]

This is my code :

class Solution:
def allPathsSourceTargetUtil(self, n, graph, visited, ans):
    visited.append(n)
    
    if n == len(graph)-1:
        ans.append(visited)
        print(ans)
    else:
        for i in graph[n]:
            self.allPathsSourceTargetUtil(i, graph, visited, ans)
        
            visited.pop()
    
    
def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]:
    ans  = []
    visited = []
    n = 0
    
    self.allPathsSourceTargetUtil(n, graph, visited, ans)
    
    return ans

And this is input:

[[1,2],[3],[3],[]]

And real Output:

[[0,1,3],[0,2,3]]

But I get this output from my code:

[[0, 1, 3]]
[[0, 2, 3], [0, 2, 3]]

[[0],[0]]

Please help me for find out problem in this code.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文