Sponsored
Sponsored
The Depth First Search (DFS) approach uses a recursive function to explore all paths from the source node to the target node by traversing each possible node in a depth-first manner. This involves exploring as far as possible along each branch before backing up.
Time Complexity: O(2^n) - since every node could lead to every other node, creating exponential paths.
Space Complexity: O(n) - the maximum depth of the recursion, and path storage could be O(n) as well.
1from typing import List
2
3def allPathsSourceTarget(graph: List[List[int]]) -> List[List[int]]:
4 def dfs(node: int, path: List[int]):
5 path.append(node)
6 if node == len(graph) - 1:
7 result.append(list(path))
8 else:
9 for next_node in graph[node]:
10 dfs(next_node, path)
11 path.pop()
12
13 result = []
14 dfs(0, [])
15 return result
In Python, the solution is built using the dfs function that manages recursion. Starting from node 0, the path is extended as nodes are visited. If the target node is encountered, the path is stored in the result variable.
The Breadth First Search (BFS) approach uses a queue to explore nodes level by level, tracking each path as it progresses. This is an iterative process that can make finding all possible paths easier to visualize compared to recursive methods like DFS.
Time Complexity: O(2^n) - Because each node may lead to different paths creating an exponential number of routes.
Space Complexity: O(2^n) - Required for holding all potential paths in the queue.
1
public class Solution {
public IList<IList<int>> AllPathsSourceTarget(int[][] graph) {
var results = new List<IList<int>>();
var queue = new Queue<List<int>>();
queue.Enqueue(new List<int> {0});
while (queue.Count > 0) {
var path = queue.Dequeue();
int lastNode = path[path.Count - 1];
if (lastNode == graph.Length - 1) {
results.Add(new List<int>(path));
} else {
foreach (var next in graph[lastNode]) {
var newPath = new List<int>(path) {next};
queue.Enqueue(newPath);
}
}
}
return results;
}
}
For the C# BFS approach, paths are managed in a queue, processing them level by level. Each path dequeued checks the end node: if it's the target, the path is recorded. Otherwise, it explores connecting nodes to build further paths.