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.
1#include <stdio.h>
2#include <stdlib.h>
3
4void dfs(int node, int n, int** graph, int* graphColSize, int* path, int pathLen, int** result, int* returnSize, int** returnColumnSizes) {
5 path[pathLen++] = node;
6 if (node == n - 1) {
7 result[*returnSize] = malloc(pathLen * sizeof(int));
8 for (int i = 0; i < pathLen; i++)
9 result[*returnSize][i] = path[i];
10 (*returnColumnSizes)[*returnSize] = pathLen;
11 (*returnSize)++;
12 } else {
13 for (int i = 0; i < graphColSize[node]; i++)
14 dfs(graph[node][i], n, graph, graphColSize, path, pathLen, result, returnSize, returnColumnSizes);
15 }
16}
17
18int** allPathsSourceTarget(int** graph, int graphSize, int* graphColSize, int* returnSize, int** returnColumnSizes) {
19 int** result = malloc(1000 * sizeof(int*));
20 *returnColumnSizes = malloc(1000 * sizeof(int));
21 int* path = malloc(15 * sizeof(int));
22 *returnSize = 0;
23 dfs(0, graphSize, graph, graphColSize, path, 0, result, returnSize, returnColumnSizes);
24 free(path);
25 return result;
26}
This C solution implements a depth-first search (DFS) recursively. The function "dfs" is called with each node and adds the node to the current path. If the current node is the target node, the path is added to the result. Otherwise, the function is called recursively for each of the node's children. Memory is dynamically allocated for the paths and adjusted for recursion depth.
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
In JavaScript, BFS is used to manage the path queue. Each iteration examines a path's most current node. If it's the last node, the path joins the results. Otherwise, node connections expand the path in upcoming iterations, tracing all possibilities to the target.