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 neededdef 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 pathvisited[source] = Truepath.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 vertexwhile graph.graph[source] is not None:i = graph.graph[source].vertexif 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 unvisitedpath.pop()visited[source] = Falsedef 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 visitedvisited = [False] * (graph.V)# Create a list to store pathspaths = []path = []# Call the recursive helper function to find all pathsfind_all_paths_recursive(graph, source, destination, visited, path, paths)return paths# Main program to test above functionif __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 = 0destination = 5paths = find_all_paths(g, source, destination)print(paths)
Explanation
If we ...
Access this course and 1400+ top-rated courses and projects.