Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find all paths with cycles in directed graph, given the source vertex

I'm having trouble solving this problem. I have to find all simple paths starting from a source vertex s containing a simple cycle in a directed graph. i.e. No repeats allowed, except of course for the single repeated vertex where the cycle joins back on the path.

I know how to use a DFS visit to find if the graph has cycles, but I can't find a way to use it to find all such paths starting from s.

For example, in this graph

        +->B-+
        |    v
s-->T-->A<---C
        |    ^
        +->D-+

Starting from s, the path S-T-A-B-C-A will correctly be found. But the path S-T-A-D-C-A will not be found, because the vertex C is marked as Visited by DFS.

Can someone hint me how to solve this problem? Thanks

like image 900
Jubstuff Avatar asked Jan 16 '12 20:01

Jubstuff


People also ask

How do you find all possible paths in a directed graph?

Finding all the possible paths in any graph in Exponential. It can be solved by using Backtracking. For DAG's we can do it using Depth first search(DFS). In DFS code, Start at any node, Go to the extreme dead end path and note down all the nodes visited in that path using some array or list.

Can DFS find all paths?

If you want to all simple paths between two nodes, you can do it with DFS with "local" visited set (that deletes a node from the visited set when it tracks back). @GarethRees Assume there is a polynomial time (NOT pseudo polynomial) algorithm for k th shortest simple path between two nodes.

How do you count the paths between vertices?

Algorithm: Create a recursive function that takes index of node of a graph and the destination index. Keep a global or a static variable count to store the count. Keep a record of the nodes visited using a visited array and while returning mark the current node to be unvisited to discover other paths.


1 Answers

This is actually quite an easy algorithm, simpler than DFS. You simply enumerate all paths in a naive recursive search, remembering not to recurse any further any time the path loops back on itself:

(This is just a Python-inspired pseudocode. I hope it's clear enough.)

 def find_paths_with_cycles(path_so_far):
       node_just_added = path_so_far.back()
       for neigh in out_neighbours(node_just_added):
           if neigh in path_so_far:
               # this is a cycle, just print it
               print path_so_far + [neigh]
           else:
               find_paths_with_cycles(path_so_far + [neigh])


 initial_path = list()
 initial_path.append(s)
 find_paths_with_cycles(initial_path)
like image 148
Aaron McDaid Avatar answered Sep 21 '22 03:09

Aaron McDaid