sophryu99 / algorithm

algorithm in python - 4 questions a week
4 stars 1 forks source link

797. All Paths From Source to Target #8

Open sophryu99 opened 1 year ago

sophryu99 commented 1 year ago

Approach

https://leetcode.com/problems/all-paths-from-source-to-target/description/

DFS through the DAG Since the size of the input node is 2 <= n <= 15, the approach does not need to be super efficient

  1. Start from the first node and traverse through the directed edges by calling dfs iteratively
  2. Have the path saved as the parameter to the dfs function
  3. When the traversal reaches the end node (n), append the path to the result and end traversing
class Solution:
    def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]:

        def dfs(path):
            if path[-1] == len(graph) - 1:
                res.append(path)
                return

            for v in graph[path[-1]]:
                dfs(path + [v])

        res = []
        dfs([0])
        return res

n: number of edges

https://leetcode.com/problems/all-paths-from-source-to-target/solutions/986429/python-iterative-dfs-with-detailed-time-complexity-visuals/?orderBy=most_votes