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
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With