Leetcode 797: All Paths From Source to Target

grid47
grid47
Exploring patterns and algorithms
Aug 19, 2024 6 min read

A graph where all paths are traced from source to target, with each path softly glowing as it is found.
Solution to LeetCode 797: All Paths From Source to Target Problem

You are given a directed acyclic graph (DAG) with n nodes, labeled from 0 to n-1. Find all possible paths from node 0 to node n-1 and return these paths in any order. The graph is represented such that each node has a list of other nodes that can be visited directly from it.
Problem
Approach
Steps
Complexity
Input: The input is a list of lists, where `graph[i]` contains all the nodes you can visit directly from node `i`.
Example: Input: graph = [[1, 2], [3], [3], []]
Constraints:
• 2 <= n <= 15
• 0 <= graph[i][j] < n
• graph[i][j] != i (no self-loops)
• All elements in graph[i] are unique
• The input graph is guaranteed to be a DAG
Output: The output should be a list of all possible paths from node 0 to node n-1. Each path is represented as a list of nodes, starting from node 0 and ending at node n-1.
Example: Output: [[0, 1, 3], [0, 2, 3]]
Constraints:
• The answer will be a list of lists, where each list represents a valid path from node 0 to node n-1.
Goal: The goal is to find all paths starting from node 0 to node n-1, respecting the directed edges in the graph.
Steps:
• Use a breadth-first search (BFS) or depth-first search (DFS) approach to explore the graph starting from node 0.
• For each node, explore all possible nodes it can lead to by following the directed edges.
• Once you reach node n-1, add the path to the result.
• If a node cannot lead to node n-1, backtrack and explore other paths.
Goal: Ensure that the graph follows the specified constraints.
Steps:
• The graph must be a valid directed acyclic graph (DAG).
• Each node has a unique set of nodes it can lead to.
• The graph must contain at least two nodes.
Assumptions:
• The graph is non-cyclic, meaning it does not contain any cycles.
• The graph has at least two nodes (i.e., node 0 and node n-1).
Input: Input: graph = [[1, 2], [3], [3], []]
Explanation: In this graph, node 0 can reach nodes 1 and 2, node 1 can reach node 3, and node 2 can also reach node 3. The two possible paths from node 0 to node 3 are [0, 1, 3] and [0, 2, 3].

Input: Input: graph = [[4, 3, 1], [3, 2, 4], [3], [4], []]
Explanation: This graph has multiple paths from node 0 to node 4: [0, 4], [0, 3, 4], [0, 1, 3, 4], [0, 1, 2, 3, 4], and [0, 1, 4].

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus