Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find all results of topological sorting

Since the results in topological sorting are not unique, there are other reasonable results. I have some relations like a->b b->c... etc. These relations are parts of a graph. I need to find all lists between root and destination(just one destination). Let root n, and destination i.

n-a-b-i

n-a-d-i

n-c-b-i

n-c-d-i

I thought i can reach these results using topological sorting but how? Thanks in advance.

like image 486
Gary Leather Avatar asked Nov 23 '25 14:11

Gary Leather


1 Answers

You shouldn't need topological sorting. Just use either breadth-first search or depth-first search from the root and store all paths that end at the destination.

Example pseudocode DFS:

paths_to_destination = []

def dfs_store_destination(node, dest, path=None):
    if path is None:
         path = []

    Append node to path

    if node == dest:
        Add path to paths_to_destination
    else:
        for new_node in node.reachable_nodes:
            dfs_store_destination(new_node, dest, path)

    Remove node from path

dfs_store_destination(root, my_dest)
like image 157
Platinum Azure Avatar answered Nov 26 '25 04:11

Platinum Azure



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!