Given a directed acyclic graph (DAG) of n nodes labeled from 0 to n - 1, find all possible paths from node 0 to node n - 1 and return them in any order.
The graph is given as follows: graph[i] is a list of all nodes you can visit from node i (i.e., there is a directed edge from node i to node graph[i][j]).
Input: graph = [[1,2],[3],[3],[]]
Output: [[0,1,3],[0,2,3]]
Explanation: There are two paths: 0 -> 1 -> 3 and 0 -> 2 -> 3.
Input: graph = [[4,3,1],[3,2,4],[3],[4],[]]
Output: [[0,4],[0,3,4],[0,1,3,4],[0,1,2,3,4],[0,1,4]]
n == graph.length2 <= n <= 150 <= graph[i][j] < ngraph[i][j] != i (i.e., there will be no self-loops).graph[i] are unique.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.
0. Explore each path by recursively visiting each node's neighbors.n-1, add a copy of the path to the result list.2^n paths, and each path can be of length n.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.
0.n-1, add it to the results.