...

/

Solution: Find All Paths Between Two Nodes

Solution: Find All Paths Between Two Nodes

This review provides a detailed analysis of the solution to find all paths between two nodes.

We'll cover the following...

Solution:

import copy # For deep copy if needed
def find_all_paths_recursive(graph, source, destination, visited, path, paths):
"""
Finds all paths between source and destination in given graph
:param graph: A directed graph
:param source: Source Vertex
:param destination: Destination Vertex
:param visited: A list to mark visited vertices
:param path: List to store one path to source from destination
:param paths: 2D list to store all paths
"""
# Mark the current node as visited and store in path
visited[source] = True
path.append(source)
# If current vertex is same as destination, then print
# stores the current path in 2D list (Deep copy)
if source == destination:
paths.append(copy.deepcopy(path))
else:
# If current vertex is not destination
# Recur for all the vertices adjacent to this vertex
while graph.graph[source] is not None:
i = graph.graph[source].vertex
if not visited[i]:
find_all_paths_recursive(graph, i, destination, visited, path, paths)
graph.graph[source] = graph.graph[source].next
# Remove current vertex from path[] and mark it as unvisited
path.pop()
visited[source] = False
def find_all_paths(graph, source, destination):
"""
Finds all paths between source and destination in given graph
:param graph: A directed graph
:param source: Source Vertex
:param destination: Destination Vertex
"""
# Mark all the vertices as not visited
visited = [False] * (graph.V)
# Create a list to store paths
paths = []
path = []
# Call the recursive helper function to find all paths
find_all_paths_recursive(graph, source, destination, visited, path, paths)
return paths
# Main program to test above function
if __name__ == "__main__":
g = Graph(6)
g.add_edge(0, 1)
g.add_edge(0, 2)
g.add_edge(1, 3)
g.add_edge(1, 4)
g.add_edge(3, 5)
g.add_edge(4, 5)
g.add_edge(2, 5)
source = 0
destination = 5
paths = find_all_paths(g, source, destination)
print(paths)

Explanation

If we ...

Access this course and 1400+ top-rated courses and projects.