AlgoMaster Logo

All Paths From Source to Target

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. DFS Backtracking

Intuition:

The problem is essentially asking for all paths from node 0 to node n-1 in a Directed Acyclic Graph (DAG). DFS (Depth First Search) is well-suited for exploring all possibilities in the graph. By using a backtracking approach, we can explore each path from the source to the target and backtrack once we reach the end to explore alternative paths.

Steps:

  1. Start DFS from node 0. Explore each path by recursively visiting each node's neighbors.
  2. Maintain a path list and whenever a node is visited, append it to the path.
  3. If the current node is the target node n-1, add a copy of the path to the result list.
  4. Backtrack by removing the node from the path list before exploring other neighbors.
  5. Return all paths found once DFS exploration is complete.

Code:

2. BFS Using a Queue

Intuition:

You can also solve this problem using BFS. The goal of BFS is to explore all neighbors at the present depth before moving on to nodes at the next depth level. By storing paths in the queue, at each step, when you explore a node, you construct and enqueue new paths adding each of the node's neighbors.

Steps:

  1. Initialize a queue and add the initial path starting from node 0.
  2. While the queue is not empty, pop paths from the queue.
  3. Extend each path by appending each of the current node's neighbors and enqueue the new path.
  4. If a path reaches the target node n-1, add it to the results.
  5. Continue until all paths are explored.

Code: