📌  相关文章
📜  从入度为 0 的顶点打印 DAG 中所有可能的路径

📅  最后修改于: 2021-10-25 03:09:12             🧑  作者: Mango

给定一个有向无环图 (DAG),有N个顶点和M 个边,任务是打印从入度为零的顶点开始的所有路径。

例子:

方法:

  1. 创建一个布尔数组indeg0 ,它存储所有入度为零的顶点的真值。
  2. 对所有入度为 0 的顶点应用 DFS。
  3. 打印从入度为 0 的顶点到出度为零的顶点的所有路径。

下面是上述方法的实现:

Python3
# Python program to print all
# possible paths in a DAG
 
# Recursive function to print all paths
def dfs(s):
    # Append the node in path
    # and set visited
    path.append(s)
    visited[s] = True
 
    # Path started with a node
    # having in-degree 0 and
    # current node has out-degree 0,
    # print current path
    if outdeg0[s] and indeg0[path[0]]:
        print(*path)
 
    # Recursive call to print all paths
    for node in adj[s]:
        if not visited[node]:
            dfs(node)
 
    # Remove node from path
    # and set unvisited
    path.pop()
    visited[s] = False
 
 
def print_all_paths(n):
    for i in range(n):
 
        # for each node with in-degree 0
        # print all possible paths
        if indeg0[i] and adj[i]:
            path = []
            visited = [False] * (n + 1)
            dfs(i)
 
 
# Driver code
from collections import defaultdict
 
n = 6
# set all nodes unvisited
visited = [False] * (n + 1)
path = []
 
# edges = (a, b): a -> b
edges = [(5, 0), (5, 2), (2, 3),
         (4, 0), (4, 1), (3, 1)]
 
# adjacency list for nodes
adj = defaultdict(list)
 
# indeg0 and outdeg0 arrays
indeg0 = [True]*n
outdeg0 = [True]*n
 
for edge in edges:
    u, v = edge[0], edge[1]
    # u -> v
    adj[u].append(v)
 
    # set indeg0[v] <- false
    indeg0[v] = False
 
    # set outdeg0[u] <- false
    outdeg0[u] = False
 
print('All possible paths:')
print_all_paths(n)


输出:
All possible paths:
4 0
4 1
5 0
5 2 3 1

时间复杂度: O (N + E) 2
辅助空间: O(N)

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程。