Find All Paths from Source to Target

beginner
15 min

Find All Paths from Source to Target

Welcome to this comprehensive guide on finding all paths from a source to a target in a graph! This lesson is designed for both beginners and intermediate learners, and we'll dive into the concept from the ground up.

Understanding Graphs šŸŽÆ

A graph is a collection of nodes (also called vertices) and edges. In our context, nodes represent the points in the graph, and edges represent the connections between these points.

Paths and Depth-First Search (DFS) šŸ“

A path in a graph is a sequence of nodes connected by edges. The goal is to find all paths from a source node to a target node. We'll use Depth-First Search (DFS) to achieve this. DFS explores as far as possible along each branch before backtracking.

Implementing DFS āœ…

To implement DFS, we'll create a recursive function that checks every unvisited neighbor of the current node. Let's see a practical example:

python
def dfs(vertex, target, visited, adjacency_list): visited[vertex] = True print(vertex) for neighbor in adjacency_list[vertex]: if not visited[neighbor]: dfs(neighbor, target, visited, adjacency_list) if vertex == target: print("Path found:", path) # Example usage: graph = { 'A': ['B', 'C'], 'B': ['A', 'D', 'E'], 'C': ['A', 'G'], 'D': ['B'], 'E': ['B', 'F'], 'F': ['E'], 'G': ['C'] } visited = [False] * len(graph) path = [] dfs('A', 'E', visited, graph)

In the example above, we have a simple graph with nodes A, B, C, D, E, F, and G. The goal is to find all paths from A to E.

Finding All Paths šŸ’”

To find all paths, we'll modify our DFS function to store the path as we traverse the graph. Here's an updated version of the function:

python
def dfs(vertex, target, visited, parent, path, adjacency_list): visited[vertex] = True path[vertex] = parent[vertex] print(path) for neighbor in adjacency_list[vertex]: if not visited[neighbor]: dfs(neighbor, target, visited, parent, path, adjacency_list) # Example usage: graph = { 'A': ['B', 'C'], 'B': ['A', 'D', 'E'], 'C': ['A', 'G'], 'D': ['B'], 'E': ['B', 'F'], 'F': ['E'], 'G': ['C'] } visited = [False] * len(graph) path = [None] * len(graph) parent = {vertex: None for vertex in graph} dfs('A', 'E', visited, parent, path, graph)

In this updated example, we store the parent of each vertex in the parent dictionary. This allows us to backtrack and print the full path when we find the target node.

Quiz Time šŸŽÆ

Question: What is the primary goal of Depth-First Search (DFS) in finding all paths from a source to a target in a graph? A: Finding the shortest path B: Finding all paths C: Finding the longest path Correct: B Explanation: DFS is used to find all paths from a source to a target in a graph.


Hope this lesson was helpful! Keep practicing, and happy coding! šŸš€šŸ’»šŸŽ“